Inline classes are introduced by Kotlin since Kotlin 1.3 version to overcome the shortcomings of traditional wrappers around some types.These Inline classes add the goodness of Typealiases with the value range of the primitive data types.
Let us suppose that we are selling some items and the cost is defined as a float type.This is depicted in the following data class
data class Items(val itemno: Int, val cost: float, val qty: Int)
If we support two types of currencies like dollar and rupees, we need to refactor cost in another class.
Java
data class Items(val itemno: Int, val cost: Cost, val qty: Int)
data class Cost(val value: Float, val currency: Currency)
enum class Currency {
RUPEE,
DOLLAR
}
|
The above method has two problems:
1.Memory overhead
2.Complexity
These two problems are overcome by Inline classes
Java
data class Item(val id: Int, val price: RupeePrice, val qty: Int)
inline class RupeePrice(val price: Float) {
inline fun toDollars(): Float = price * 71 .62f
}
|
An inline class must have a single property initialized in the primary constructor. At runtime, instances of the inline class will be represented using this single property:data of the class is “inlined” into its usages (That’s why the name “Inline classes”).
Members
They are similar to regular classes in the sense that they are allowed to declare properties and functions.However, they have certain limitations too.Inline classes cannot have init blocks nor can they have complex computable properties like lateinit/delegated properties.
Java
inline class Name(val s: String) {
val length: Int
get() = s.length
fun greet() {
println( "Hello, $s" )
}
}
fun main() {
val name = Name( "Kotlin" )
name.greet()
println(name.length)
}
|
Inheritance
These classes are allowed to inherit from Interfaces but can not extend other classes and must be final
Java
interface Printable {
fun prettyPrint(): String
}
inline class Name(val s: String) : Printable {
override fun prettyPrint(): String = "Let's $s!"
}
fun main() {
val name = Name( "Kotlin" )
println(name.prettyPrint())
}
|
Representation
Inline classes can be represented as either wrappers or underlying type.Though the latter is preferred, sometimes it is useful to keep wrappers around.Necessarily they are boxed whenever used as other type. Referential equality is meaningless as it can be represented both as an underlying value and as a wrapper.
Java
interface I
inline class Foo(val i: Int) : I
fun asInline(f: Foo) {}
fun asGeneric(x: T) {}
fun asInterface(i: I) {}
fun asNullable(i: Foo?) {}
fun id(x: T): T = x
fun main() {
val f = Foo( 42 )
asInline(f)
asGeneric(f)
asInterface(f)
asNullable(f)
val c = id(f)
}
|
As an underlying type, these inline classes may lead to obscure errors like platform signature crashes.
Java
inline class UInt(val x: Int)
fun compute(x: Int) { }
fun compute(x: UInt) { }
|
To prevent such errors we use a process called Mangling where we add some hashcode to function name.Therefore, fun compute(x: UInt) will be represented as public final void compute-(int x), which solves the problem.
Inline classes vs type aliases
Though both may appear similar, the type aliases are assignment-compatible with underlying type. Also inline classes introduce a completely new type whereas type aliases give an alternate name for existing type
Java
typealias NameTypeAlias = String
inline class NameInlineClass(val s: String)
fun acceptString(s: String) {}
fun acceptNameTypeAlias(n: NameTypeAlias) {}
fun acceptNameInlineClass(p: NameInlineClass) {}
fun main() {
val nameAlias: NameTypeAlias = ""
val nameInlineClass: NameInlineClass = NameInlineClass( "" )
val string: String = ""
acceptString(nameAlias)
acceptString(nameInlineClass)
acceptNameTypeAlias(string)
acceptNameInlineClass(string)
}
|
The design of inline classes is new and no compatibility guarantees are given.In Kotlin 1.3+, a warning will be reported, indicating that this feature is experimental.To remove this we have to opt in to the usage of this experimental feature by passing the compiler argument -Xinline-classes.
Similar Reads
Enum Classes in Kotlin
In programming, sometimes there arises a need for a type to have only certain values. To accomplish this, the concept of enumeration was introduced. Enumeration is a named list of constants. In Kotlin, like many other programming languages, an enum has its own specialized type, indicating that somet
5 min read
Closures in Kotlin
According to Kotlin's official documentation "A closure is a special kind of object that combines two things: a function, and the environment in which that function was created. The environment consists of any local variables that were in-scope at the time the closure was created" var sum = 0 ints.f
2 min read
Kotlin Data Classes
We often create classes to hold some data in it. In such classes, some standard functions are often derivable from the data. In Kotlin, this type of class is known as data class and is marked as data. Example of a data : data class Student(val name: String, val roll_no: Int) The compiler automatical
4 min read
Kotlin Inline Functions
In Kotlin, the higher-order functions or lambda expressions, all stored as an object so memory allocation, for both function objects and classes, and virtual calls might introduce runtime overhead. Sometimes we can eliminate the memory overhead by inlining the lambda expression. In order to reduce t
5 min read
Kotlin Sealed Classes
Kotlin provides an important new type of class that is not present in Java. These are known as sealed classes. As the word sealed suggests, sealed classes conform to restricted or bounded class hierarchies. A sealed class defines a set of subclasses within it. It is used when it is known in advance
3 min read
Singleton Class in Kotlin
Singleton Class in Kotlin is also called as the Singleton Object in Kotlin. Singleton class is a class that is defined in such a way that only one instance of the class can be created and used everywhere. Many times we create the two different objects of the same class, but we have to remember that
4 min read
Kotlin Nested class and Inner class
Nested Class In Kotlin, you can define a class inside another class, which is known as a nested class. Nested classes have access to the members (fields and methods) of the outer class. Here is an example of a nested class in Kotlin: C/C++ Code class Car { var make: String var model: String var year
5 min read
Type Aliases vs Inline Classes
Kotlin is a programming language which brings all the powers of modern programming languages to android development. In this article, we will discuss about it's two cool features namely Type Aliases and Inline Classes. Type Aliases Let's suppose you are creating a project where you defined two class
2 min read
How to Get the Class in Kotlin?
Kotlin is a statically typed, general-purpose programming language developed by JetBrains, that has built world-class IDEs like IntelliJ IDEA, PhpStorm, Appcode, etc. It was first introduced by JetBrains in 2011 and is a new language for the JVM. Kotlin is an object-oriented language, and a âbetter
3 min read
Delegation in Kotlin
Delegation controls the allocation of power/authority from an instance to another for any object. For classes and functions implementations, delegations can be used on static as well as mutable relations between them. Inheritance implementation in classes and functions can be altered with the help o
3 min read