no idea where to ask this, but I am experimenting ...
# announcements
t
no idea where to ask this, but I am experimenting with inline classes. Quite awesome feature imo, except
toString
does not seem consistent (given my understanding that inline classes are substituted with their member) given
Copy code
inline class ProjectUid(val projectUid: String)
println(ProjectUid("test"))
the output is
ProjectUid(projectUid=test)
, I would have expected only
test
. This "breaks" some libraries (simple workaround is to inline myself) am I misundersting something? is this behavior expected?
d
Inline classes are not like type aliases. They behave as if they were regular classes, but when possible the compiler can eliminate their objects (like with primitives). In your example you are passing the instance of the inline class to
println
, which expects
Any?
, so the compiler has to create a boxing operation to preserve the semantics (proper toString).
l
You can define your own
toString()
overriding method. And as said above, this is not like type aliases.
t
I see. It is a bit counterintuitive but makes sense. Thanks
l
It is still a class. I don't see what is counterintuitive in this behavior, it is rather consistent. If you want to print the internal value, then get the value and print it instead of printing the wrapping inline class. BTW, your example implies autoboxing, which would not be the case if you get the wrapped value before passing it to a function accepting
Any
a
IMO the boxing isn't needed here. Boxing is necessary if the inline class implements an interface and needs to be passed to a function. In this case
println
already expects
Any
, so it would be fine to pass in the underlying string instead of a boxed version
l
Yes the boxing is not needed, but it's there when you cast an inline class to an upper type like
Any
. The solution is to unwrap before, if possible (which it is here)
t
actually I could have avoided the question if I just read the documentation a bit deeper: https://kotlinlang.org/docs/reference/inline-classes.html#representation but the initial sentence
At runtime, instances of the inline class will be represented using this single property
(at the beginning of the page) threw me off and made think inlining was always done