Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the use cases of Kotlin inline properties?

Tags:

kotlin

As properties' getter or setter don't usually have function as argument nor reified type, what would be the benefits / use case of using inline properties?

If the benefits would be to reduce cost related to method call, why not make all properties getter/setter inline by default?

Kotlin Inline Properties

Eg.

val foo: Foo
    inline get() = Foo()

var bar: Bar
    get() = ...
    inline set(v) { ... }
like image 340
Yudhistira Arya Avatar asked Apr 08 '17 10:04

Yudhistira Arya


People also ask

Why do we use inline function Kotlin?

Inline functions are useful when a function accepts another function or lambda as a parameter. You can use an inline function when you need to prevent "object creation" and have better control flow.

What is the use of inline class in Kotlin?

An inline class is a special type of class defined in Kotlin that only has one property. At runtime, the compiler will “inline” the property where it was used. This is similar to inline functions, where the compiler inserts the contents of the function into where it was called.

What's the difference between inline and infix functions Kotlin?

The first argument is the target object, the second argument is the actual argument passed to the function. Creating the infix function is just like creating the inline function. The only difference in syntax is that we use the infix keyword instead of inline .

In which cases is a backing property created in Kotlin?

Kotlin will generate a backing field for a property if we use at least one default accessor or we reference the field identifier inside a custom accessor. Default accessors are those that are generated with val or var keywords.


1 Answers

Here is inline properties discussion:

Example of reified type parameter:

inline val <reified T : PsiElement> T.nextSiblingOfSameType: T?
    get() = PsiTreeUtil.getNextSiblingOfType(this, T::class.java)

Another use case is to hide some properties from the binary interface of a library. In Kotlin standard library, together with the @InlineOnly annotation this might make it possible in the future to exclude declarations of such properties from class files, reducing method count, this will mostly benefit Android with it's 64K method limit.

like image 183
John Avatar answered Sep 29 '22 18:09

John