Inline classes

4 0 0
                                        

inline classes - it is value-based classes since it only holds the values. This was created to support wrapper on primitive classes. If you used a wrapper on a primitive class, the performance is slow since primitive types are used more often and using a wrapper will cost you an additional memory allocation. So, the solution was to used this value-based inline class. They want the primitive data type to be inline with its usage.

Sometimes, we want the function to be inline to lessen the declaration and definition of either a variable or a function. This may save us some memory since you did not create a temporary storage for values. This may save us some time too since it lessens the programs declaration and definition. You just proceed with the whole process right away during the call outs. This is the same logic with the above inline class. You just want to proceed with the wrapping of the primitive data type right away during the call out. 

syntax: /:/ using this symbol as at sign

/:/JVMInline

value class Name(parameter1: Type){

    init{// statement}

    val property1: Type

         get() = ...

    fun methodName(){ //statement}

}

Note: 

1. As you can see, it works like a regular class but you are not allowed to use a backing field. For the property member, you are allowed to use get() explicitly but not set(). 

2. You are allowed to use init{}.

3. inline class cannot extend a class and are always final but they are allowed to extend from interfaces.

4. It automatically boxed and unboxed.

=====================

fun main(){

    val x = InlinePracticeClass("Hello Kotlin!")

    x.displaySomething()

}

/:/JVMInline

value class InlinePracticeClass(private val message: String){

     init{

         require(message.isNotEmpty())

     }

     private val prop1: Int

         get() = message.length

     fun displaySomething(){

        println("message length: $prop1")

        println(message)

    }

}

=====================

Result:

message length: 13

Hello Kotlin!


Note:

1. Mangling - it is a scheme use by the compiler to avoid clashes of names. What the compiler does is concatenate a hashcode to the name to avoid complications. But if you want to disable this, just used an annotation /:/JVMName("whatever is the name")

2. Delegation with interfaces is allowed in inline class.

syntax:

/:/JVMInline

value class Name(val x: MyInterface): MyInterface by x{

    //statement

}

Kotlin ProgrammingWhere stories live. Discover now