📌 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? 🚀
📌 Difference Between Two Kotlin Class Definitions
1️⃣ First Version (Without
varorval)Characteristics:
xandyare constructor parameters, not properties.Example of Incorrect Usage:
2️⃣ Second Version (With
var)Characteristics:
xandyare declared as mutable properties of the class.Example of Correct Usage:
3️⃣ Comparison Table
open class Point2D(x: Double, y: Double)open class Point2D(var x: Double, var y: Double)xandyare...varallows mutation)4️⃣ When to Use Each Version?
xandyinside the class (e.g., for calculations).xandyto be stored as properties and accessible externally.Would you like a real-world analogy to clarify further? 🚀