You are currently viewing What is the point of Constructor for Class instead of Var/Val?

What is the point of Constructor for Class instead of Var/Val?

I am new to Kotlin, and I don’t quite get the use of Constructor in class. Let’s compare those codes:

Constructor version:

class PersonCon constructor( firstName: String = "John", lastName: String = "Wick"){ var firstName: String var lastName: String init { this.firstName = firstName this.lastName = lastName } fun getName() : String{ return "$firstName $lastName" } } 

var/val version:

class PersonVar { var firstName = "John" var lastName = "Wick" fun getName() : String{ return "$firstName $lastName" } } 

Both classes is kinda achieving the same purpose, but the var/val version is way cleaner and provide better readability. The only downside of using var/val is that we can’t preview which variables for constructing that class. Also it will be more tedious to construct an object.

Constructing an object (Constructor version)

val p1 = PersonCon("Alice","Manson") 

Constructing an object (var/val version)

var p2 = PersonVar() p2.firstName = "Alice" p2.lastName = "Manson" 

Is there a better way that combine the advantages for both method (clean code + readability + constructor preview)?

submitted by /u/Fxavierho
[link] [comments]