Class with and without val/var confusion


Hi Kotliner,
I am getting very confused with some unpredictable compiler behaviors when to val/var in constructor and when not to use them, why such differences and benefits or such rules.
I am using almost latest kotlin version (1.2.41)

Please note, there’s no runtime differences or impact but its only related to warning/suggestion by compiler

Example : the difference is only using value inside a function or using value outside a function

//Suggesting me to remove val from constructor
class TestClass1(value: Boolean = false)
    val output = if(value) "value is true" else "value is false"

//val/var is mandatory and suggesting me to make it private
class TestClass2(private val value: Boolean = false)
    fun output() = if(value) "value is true" else "value is false"


When you write val output =... for a top level class property, it is calculated when the class instance is created, therefore, it does not need the value from the constructor anymore and suggests not to store it.

On the other hand if you use function or dynamic accessor like val output: String get()=..., the value is calculated each time you call it. Therefore the value it is based upon must be remembered by the class instance.


Class property initializers have access to primary constructor’s args.

Within function body you cannot access primary constructor’s args. In this case you need to declare the constructor args as properties.