Value classes within string templates

I have a question regarding value classes (before inline) and string templates. Suppose I have the following code:

value class Data(val value: String)

fun main(args: Array<String>) {
    val value = Data("Data")
    println("Value = $value")

The output of the code is as follows:

Value = Data(value=Data)

What is the reason to output the value class like that in a string template instead of just the value (without the wrapper class)?

Of course I can achive that by implementing a custom toString like so:

value class Data(val value: String) {
    override fun toString(): String {
        return value

but I actually expected it to work this way out of the box. Perhaps I am misunderstanding something.

1 Like

The current solution makes sense in my opinion. When JVM will finally support value classes on bytecode level then it would be possible to have classes with multiple properties not just one. The better option then is to stick with the current convention rather than use a one depending on the number of properties.


It’s also the same behaviour as data classes have.

Current solution makes more sense to me. Representing a variable as an unboxed value is internal optimization, but conceptually it is still an instance of a class.

Yeah, from that perspective it makes sense indeed. For now I am adding the custom toString() method so the unboxed value is printed when I use the value in a String template.

1 Like