Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin object. Which way of initialization is right?

Tags:

kotlin

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>() ....
like image 628
Dmitry Zlykh Avatar asked Nov 27 '25 21:11

Dmitry Zlykh


1 Answers

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.

like image 60
Alexander Udalov Avatar answered Nov 30 '25 23:11

Alexander Udalov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!