I am trying to understand inline classes in kotlin
fun main(){
val password = Password("Current Password")
println(password)
println(password.password)
}
inline class Password(val password: String)
This is a sample code I wrote according to the documentation. Now they said no instantiation of class Password will happen.
My output should be
Current Password
Current Password
But I am getting
Password(password=Current Password)
Current Password
If instantiation doesn't happen, then when we try to access password variable directly we should access it as a common string right?
It's not compiled to an object so long as you don't use it in a nullable or generic context. If you do, it will get wrapped in an object just like the primitives do.
But the toString()
and other functions and properties are still available to use as if it were a class, just like they are for primitives. I don't know the exact mechanism in compiled code, but I am guessing they are realized in the same way as extension functions (which on JVM are compiled as static methods with the "receiver" as another argument).
From your point of view, you still treat it exactly as any of the primitive classes, which have wrapper versions for when they are nullable or used as generics. But you have the added benefit of being able to override toString()
and adding functions without using extensions.