so I've got this class: ```class Foo { val data:...
# getting-started
y
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
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
okay, I like that. cool. thank you.
k
What's the advantage of using the constructor over initializing at the point of declaration?
y
as in, lazy init?
k
No, as in
val data = mapOf(Fizz to Buzz)
instead of doing the same thing through a private constructor.
y
I'm not sure I understand. the values in
data
need to be populated for
doSomeInit()
to do its thing
e
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
lazy init does, though