Rob Elliot
11/03/2021, 11:16 AMRob Elliot
11/03/2021, 11:17 AMinterface A {
val x: String
val y: Int
}
interface B {
val x: String
val y: Int
fun z(): Boolean
}
you could adapt any A
to be a B
using some terse syntax like this:
type A : B {
override fun z(): Boolean = x.toIntOrNull() == y
}
and the compiler could prove that an instance of A
is now a B
and can be used wherever a B
is needed without needing to call a function to adapt it.Rob Elliot
11/03/2021, 11:24 AMclass AtoBAdapter(a: A): B {
override val x: String = a.x
override val y: Int = a.y
override fun z(): Boolean = x.toIntOrNull() == y
}
fun A.asB() = AtoBAdapter(this)
and of course requires me to call a.asB()
whenever I need to pass an A
to something that needs a B
.spand
11/03/2021, 11:32 AMspand
11/03/2021, 11:35 AMRob Elliot
11/03/2021, 11:37 AMAtoBAdapter
a value class
then I still have to declare all the members which B
shares with A
, and I still have to call a function whenever I need to convert an A
to a B
, even if that function were inlined
(Though when I experimented with this I found that in order to make AtoBAdapter
implement B
it had to box it, so I didn’t bother.)Rob Elliot
11/03/2021, 11:38 AMDavid Silva
11/03/2021, 11:45 AMA
as well and rely on delegation, which might definitely be a bit odd tbh
class AtoBAdapter(a: A): A by a, B {
override fun z(): Boolean = x.toIntOrNull() == y
}
Rob Elliot
11/03/2021, 11:47 AMclass AtoBAdapter(a: A): B by a {
override fun z(): Boolean = x.toIntOrNull() == y
}
Can
11/03/2021, 11:54 AMCan
11/03/2021, 12:31 PMRob Elliot
11/03/2021, 12:38 PMasB
extension function:
fun A.asB(): B = object : A by this, B {
override fun z(): Boolean = x.toIntOrNull() == y
}
Not sure if there are any performance implications of the anonymous inner class there?
Makes the adaptation from B
to A
very simple:
fun B.asA(): A = object : B by this, A {}
Can
11/03/2021, 1:26 PMRob Elliot
11/03/2021, 1:26 PMCan
11/03/2021, 1:27 PMA by this
might work for certain use-cases but certainly not for all (especially not for closed A
types)jimn
11/03/2021, 1:40 PM