The code doesn’t compile because compiler can’t see difference between engine
field and engine
method.
class Car {
class Builder {
lateinit var engine: Engine
fun engine(obj: Engine): Builder {
this.engine = obj
return this
}
fun build(): Car {
val stringId = engine.id.toString()
if (!this::engine.isInitialized) {
throw RuntimeException("engine is not defined")
}
return Car()
}
class Engine(val id: Int) {
fun id(): Int {
return id
}
}
}
}
But that seems should be clear for compiler because class method
doesn’t have meta field isInitialized
, but class field
has. Like it happens with regular fields:
val stringId = engine.id.toString()