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.

Sourav Kannantha B
  • 2,860
  • 1
  • 11
  • 35
  • 1
    isn;t that because inline classes are still in beta? https://blog.jetbrains.com/kotlin/2021/02/new-language-features-preview-in-kotlin-1-4-30/ -> 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 Feb 07 '21 at 10:10

1 Answers1

0

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

Commander Tvis
  • 2,244
  • 2
  • 15
  • 41