https://kotlinlang.org logo
#getting-started
Title
# getting-started
y

y

12/14/2023, 1:55 PM
so I've got this class:
Copy code
class Foo {
  val data: Map<Fizz, Buzz>
  
  init {
    data = getData() 
    doSomeInit() //function uses this.data
  }
}
this also compiles, unfortunately
Copy code
class Foo {
  val data: Map<Fizz, Buzz>
  
  init {
    doSomeInit() //function uses this.data
    data = getData() 
  }
}
is there any way to at least assert that
data
is initialized, like with
isInitialized
(which is only available on `lateinit var`s)?
e

ephemient

12/14/2023, 1:58 PM
no, but if you write
Copy code
class Foo(
    val data: Map<Fizz, Buzz>
)
or possibly
Copy code
class Foo private constructor(
    val data: Map<Fizz, Buzz>
) {
    constructor() : this(mapOf(Fizz to Buzz))
then it will definitely be initialized before any other code in the class body
1
y

y

12/14/2023, 1:59 PM
okay, I like that. cool. thank you.
k

Klitos Kyriacou

12/14/2023, 4:18 PM
What's the advantage of using the constructor over initializing at the point of declaration?
y

y

12/14/2023, 4:18 PM
as in, lazy init?
k

Klitos Kyriacou

12/14/2023, 4:19 PM
No, as in
val data = mapOf(Fizz to Buzz)
instead of doing the same thing through a private constructor.
y

y

12/14/2023, 4:20 PM
I'm not sure I understand. the values in
data
need to be populated for
doSomeInit()
to do its thing
e

ephemient

12/14/2023, 4:20 PM
it doesn't prevent
Copy code
init {
    doSomeInit()
}

val data = getData()

fun doSomeInit() {
    // uses data
that function will run with uninitialized
data
(e.g.
null
, bypassing safety checks)
y

y

12/14/2023, 4:24 PM
lazy init does, though