Chills
04/01/2020, 9:11 AMdiesieben07
04/01/2020, 9:12 AMdiesieben07
04/01/2020, 9:13 AMclass Foo(val x: String) {
constructor() : super() // x is not initialized!
}
Chills
04/01/2020, 9:14 AMString
as parameter
and secondary constructor takes type T
diesieben07
04/01/2020, 9:15 AMChills
04/01/2020, 9:15 AMdiesieben07
04/01/2020, 9:15 AMChills
04/01/2020, 9:16 AMdiesieben07
04/01/2020, 9:19 AMdiesieben07
04/01/2020, 9:20 AMChills
04/01/2020, 9:22 AMclass Foo(xName:String="") {
var nick:String = xName
constructor(address:String)`:this()`{
//TODO()
}
}
Chills
04/01/2020, 9:23 AMdiesieben07
04/01/2020, 9:23 AMdiesieben07
04/01/2020, 9:24 AMChills
04/01/2020, 9:24 AMMichael de Kaste
04/01/2020, 9:25 AMvar nick
I presume)
If you just write it like this:
data class Foo(
var nick: String = ""
val address: String
)
you can do what you want with your secondary constructor by just saying:
val foo = Foo(address = "my value")
diesieben07
04/01/2020, 9:25 AMclass MyClass(val value: String)
Chills
04/01/2020, 9:27 AMMichael de Kaste
04/01/2020, 9:33 AMChills
04/01/2020, 9:34 AMMichael de Kaste
04/01/2020, 9:34 AMChills
04/01/2020, 9:35 AMChills
04/01/2020, 9:38 AMMichael de Kaste
04/01/2020, 9:41 AMfinal class TriPoint {
public final int x;
public final int y;
public final int z;
public TriPoint(int x, int y, int z){
this.x = x;
this.y = y;
this.z = z;
}
//equals, hashCode, toString, etc.
}
It's very noticable that x,y,z are the driving variables behind the whole class, whenever you initialize the class, you want to initialize x,y,z.
kotlin fixes this by lifting those variables inside what's called a primary constructor:
data class TriPoint(
val x: Int,
val y: Int,
val z: Int
)
You have effectively said to the compiler; whatever I'm doing, I need to construct x,y,z at least.Chills
04/01/2020, 9:42 AMChills
04/01/2020, 9:43 AM