Skip to content

Difference between using var/val or not when creating a Constructor #2

@JayCesar

Description

@JayCesar

📌 Difference Between Two Kotlin Class Definitions

1️⃣ First Version (Without var or val)

open class Point2D(x: Double, y: Double) {}

Characteristics:

  • x and y are constructor parameters, not properties.
  • They exist only inside the constructor and are not accessible outside the class.
  • If you want to use them inside the class, you must declare properties explicitly:
    open class Point2D(x: Double, y: Double) {
        val xPos = x  // Now xPos is a property
        val yPos = y
    }

Example of Incorrect Usage:

fun main() {
    val point = Point2D(3.0, 4.0)
    println(point.x)  // ❌ Error: Unresolved reference 'x'
}

2️⃣ Second Version (With var)

open class Point2D(var x: Double, var y: Double) {}

Characteristics:

  • x and y are declared as mutable properties of the class.
  • They are automatically stored in the object and can be accessed or modified externally.

Example of Correct Usage:

fun main() {
    val point = Point2D(3.0, 4.0)
    println(point.x)  // ✅ Works: Prints 3.0
    point.x = 5.0     // ✅ Can modify since it's `var`
    println(point.x)  // ✅ Prints 5.0
}

3️⃣ Comparison Table

Feature open class Point2D(x: Double, y: Double) open class Point2D(var x: Double, var y: Double)
x and y are... Constructor parameters only Properties of the class
Accessible outside? ❌ No ✅ Yes
Mutable? ❌ No ✅ Yes (var allows mutation)
Stored in object? ❌ No ✅ Yes

4️⃣ When to Use Each Version?

  • Use the first version if you only need x and y inside the class (e.g., for calculations).
  • Use the second version if you want x and y to be stored as properties and accessible externally.

Would you like a real-world analogy to clarify further? 🚀

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions