https://kotlinlang.org logo
#getting-started
Title
# getting-started
s

Saharath Kleips

09/01/2021, 5:59 PM
I have a question about a behavior around `value class`es. From my understanding they’re (in most cases) a zero-overhead way to make a “type-safe primitive”. But what happens in the case of collections and moving between the primitive and the value class?
Copy code
value class Box(val str: String)
val letters: List<String> = listOf("A","B","C",...)

val boxes: List<Box> = letters.map(::Box)
val backToLetters: List<String> = boxes.map(Box::str)
Are there any costs associated with moving between a
List<String>
and
List<Box>
and vice versa?
e

ephemient

09/01/2021, 6:03 PM
yes, that boxes/unboxes each element, as of it were a non-value class
🙏 1
👍 1
z

Zak Henry

09/01/2021, 6:16 PM
since the value itself would be inlined, wouldn’t the identity map be optimised away by the compiler resulting in a no-op?
e

ephemient

09/01/2021, 6:18 PM
no, inline classes have two representations
z

Zak Henry

09/01/2021, 6:24 PM
ah interesting thanks 👍
c

CLOVIS

09/02/2021, 1:21 PM
Note that this is the current behavior, but there are plans to eliminate those boxes in the future (thanks for Project Valhalla, for example)
🆒 1
s

Stephan Schroeder

09/03/2021, 2:12 PM
you know that you forgot the
@JvmInline
infront of
value class
, don't you!?
👌 1
😅 1
2 Views