Reputation: 400
Suppose you have 2 Kotlin classes
class Battery(
val carbon: Any,
val zinc: Any
)
class RemoteControl(
/* inline */ val battery: Battery,
val buttons: Any
)
Notice the commented out inline
keyword in RemoteControl
. Uncommenting it doesn't produce an error in Intellij.
Is this valid Kotlin code and what does it do?
My expectations is that it is equivalent to
class RemoteControl(
val carbon: Any,
val zinc: Any,
val buttons: Any
)
But it doesn't appear to do anything.
I'm using Kotlin 1.3.72 and Android Studio 4.0.1
Upvotes: 2
Views: 493
Reputation: 30755
The inline
modifier can be used on the property (on the property of primary constructor as well):
// var property
inline var battery: Battery
get() = Battery("carbon", "zinc")
set(v) { }
// val property
inline val battery: Battery
get() = Battery("carbon", "zinc")
// primary constructor
class RemoteControl(inline val battery: Battery)
In such a case, all accessors are marked inline automatically. At the call site the accessors are inlined as normal functions.
Applying inline to a property that has a backing field, or its accessor, results in a compile-time error:
// error: "Inline property cannot have backing field"
inline var battery: Battery
get() = Battery("carbon", "zinc")
set(v) { field = v } // we use backing field here
There is more info.
Upvotes: 2