8

This is an exact code snippet of value classes taken from kotlin official website.

interface I

@JvmInline
value class Foo(val i: Int) : I

fun asInline(f: Foo) {}
fun <T> asGeneric(x: T) {}
fun asInterface(i: I) {}
fun asNullable(i: Foo?) {}

fun <T> id(x: T): T = x

fun main() {
    val f = Foo(42) 
    
    asInline(f)    // unboxed: used as Foo itself
    asGeneric(f)   // boxed: used as generic type T
    asInterface(f) // boxed: used as type I
    asNullable(f)  // boxed: used as Foo?, which is different from Foo
    
    // below, 'f' first is boxed (while being passed to 'id') and then unboxed (when returned from 'id') 
    // In the end, 'c' contains unboxed representation (just '42'), as 'f' 
    val c = id(f)  
}

Running this on kotlin playground is giving me these two contradicting errors:
Unresolved reference: JvmInline
Value classes without @JvmInline annotation are not supported yet

I am not knowing where I've gone wrong, I just wanted to know the type of val c at the end of this code.

1
  • 1
    isn;t that because inline classes are still in beta? blog.jetbrains.com/kotlin/2021/02/… -> You define a value class with one constructor parameter and annotate it with @JvmInline. We expect everyone to use this new syntax starting from Kotlin 1.5. The old syntax inline class will continue to work for some time.
    – Stachu
    Commented Feb 7, 2021 at 10:10

1 Answer 1

1

After the release of Kotlin 1.5, value classes work normally in Kotlin Playground.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.