Inline classes: Inline classes
I want to know what is the exact difference between inline from other classes in kotlin? And I want to know what is exact inline class do and when we will use it?
An equivalent way to declare an inline member function is to either declare it in the class with the inline keyword (and define the function outside of its class) or to define it outside of the class declaration using the inline keyword.
In order to use inline classes, you would need to create a class with a single value, and prefix it with the word inline . This tells the compiler to inline the type where possible but still provides compile-time safety if we try to use the incorrect type.
Inline classes are not nullable and instead have a default value. Inline classes may declare inner, nested, local types. Inline classes are implicitly final so cannot be abstract. Inline classes implicitly extend java.
Sealed classes are used for representing restricted class hierarchies, when a value can have one of the types from a limited set, but cannot have any other type.
Inline classes are just some kind of typed wrappers over primitive types and strings.
For example, imagine we have an interface declaration like this:
interface ResizeableView {
fun resize(width: Int, height: Int)
}
Every time a developer needs to invoke this method he needs to check the parameters order first to not confuse width and height.
And still, what happens if parameters will eventually get messed up?
val width: Int = someObject.width
val height: Int = someObject.height
resizeableView.resize(height, width) //compiles ok and brings a bug to the program
This example is plain and simple, but for some other case when a method declares a bunch of primitive-typed parameters that conform to a single type, the unwanted behavior of the program can be not so easily understood and so arguments confusion detected.
Inline classes help with this:
inline class Width(val value: Int)
inline class Height(val value: Int)
interface ResizeableView {
fun resize(width: Width, height: Height)
}
Because Width
and Height
are now different types, the confusion is banished when invoking the method.
val width: Width = someObject.width
val height: Height = someObject.height
resizeableView.resize(height, width) //compile-time error
But what is the point of the inline
modifier here? Why just don't use class Width
?
The key thing is that inline classes
introduce a type only at compile type, and in runtime these variables will be just int
-s, so no runtime overhead will be created.
Here is a nice real world example of inline classes application.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With