kartikpatodi
11/05/2018, 7:12 PMclass A1(private val x: Int) {
private val y: Int = 0
}
generates this code in Java
public final class A1 {
private final int y;
private final int x;
public A1(int x) {
this.x = x;
}
}
while
class A2(private val x: Int) {
private val y: Int
init {
y = 0
}
}
generates
public final class A2 {
private final int y;
private final int x;
public A2(int x) {
this.x = x;
this.y = 0;
}
}
Why if init block y=0
is in constructor of A2
and not otherwise in case of A1
?marstran
11/05/2018, 7:15 PMkartikpatodi
11/05/2018, 7:16 PMMike
11/05/2018, 7:42 PMinit
in Kotlin is part of the construction process for a class, hence the code being emitted in the constructor.
In your simple example, you could obviously just assign 0
to y when you define it.
Help?kartikpatodi
11/05/2018, 8:01 PMclass A1(private val x: Int) {
private val y: Int = 2
}
generates
public final class A1 {
private final int y;
private final int x;
public A1(int x) {
this.x = x;
this.y = 2;
}
}
Which means it is omitting the constructor assignment only in the case of default values is supplied like 0
for Int
Which seems reasonable but if someone can confirm this.karelpeeters
11/05/2018, 8:44 PM= 0
is generated, right?Mike
11/05/2018, 8:54 PMkartikpatodi
11/06/2018, 6:46 PM