is there any difference between initialization of an object? Will the time field have different behavior or is it just the same as in Java (split declaration and initialization)? Thanks
object DataHolder {
val time : MutableList<Long>
init {
time = arrayListOf()
} ...
and this
object DataHolder {
val time = arrayListOf<Long>() ....
Generally there's no difference at all between property initialization in the assignment or in the init block. You can inspect the generated bytecode with the javap tool to find out that it's exactly the same in both cases, modulo line numbers.
In your example however, there's a difference even from the source code perspective: in the first sample time's type is declared to be MutableList<Long>, but in the second sample its type is not specified explicitly, so it has the type of the expression assigned to it. arrayListOf<T> returns ArrayList<T>, so time's type in the second case is ArrayList<Long>. If you specify MutableList<Long> as time's type in the second example, then indeed the produced outputs will be the same.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With