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

Daniel Svensson

10/05/2021, 11:35 AM
Humm... is there any way to allow passing a
value class WriteableResource(val ro: Resource)
to a method only accepting
Resource
without explicitly passing its member? Does it have to explicitly implement an interface for
Resource
?
I suspect this answers that question 😞
Copy code
interface I

@JvmInline
value class Foo(val i: Int) : I
fun asInterface(i: I) {}
val f = Foo(42)
asInterface(f) // boxed: used as type I
but at least it's possible to refer to the embedded object, so that brings compile time safety with no overhead, and any evildoings will be apparent in the code.
t

thanksforallthefish

10/05/2021, 11:59 AM
with a regular class you could do
Copy code
class WriteableResource(val ro: Resource) : Resource by ro
and you can then pass it to all methods accepting a
Resource
. but this syntax is not supported by
value
classes
d

Daniel Svensson

10/05/2021, 12:10 PM
Oh shiny, didn't know that. Neat in other cases.
I wonder if the fact that the implemented interface == the embedded type allows for avoiding the boxing. I guess I have to check the generated bytecode at some point.
@thanksforallthefish any idea if that's planned for value classes? if so, any issue to subscribe to?
t

thanksforallthefish

10/05/2021, 12:18 PM
honestly I have no idea, I don’t see a real reason why delegation should not be possible with value classes (so there might be an issue to add it somewhere). I might be missing some basic though anyway, if you find any issue let me know
d

Daniel Svensson

10/06/2021, 7:16 PM
t

thanksforallthefish

10/07/2021, 6:01 AM
thank you 🙂 it is fun how a single sentence can trigger a whole of reasoning
Currently, we should either save the result of expr somewhere...
kinda obvious why delegation for inlined classes is not “possible”, since inlined classes disappear at runtime I see how it would require workarounds. and given the change to
value
class gives a better semantic to what a value class should be for (imo, no behavior, just data) it probably makes sense to forbid a more behavior-oriented pattern such as delegation
3 Views