can anyone please explain the following behavior ...
# getting-started
k
can anyone please explain the following behavior
Copy code
class A1(private val x: Int) {
    private val y: Int = 0
}
generates this code in Java
Copy code
public final class A1 {
    private final int y;
    private final int x;

    public A1(int x) {
        this.x = x;
    }
}
while
Copy code
class A2(private val x: Int) {
    private val y: Int
    init {
        y = 0
    }
}
generates
Copy code
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
?
m
Use backtics ``` instead of ''' to format the code.
k
edited
m
init
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?
k
@Mike ok so does both express same behaviour?
also I experimented a bit and
Copy code
class A1(private val x: Int) {
    private val y: Int = 2
}
generates
Copy code
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.
👍 1
k
What's the problem? It doesn't matter whether the
= 0
is generated, right?
m
I suspect they want to better understand what gets generated, so they're digging in. As to why, only they can answer that.
k
@Mike Actually was converting some legacy java code and did not understand the reason for the behavior, but now I gotit I think..