Why can't we create generic wrapper classes, like ...
# announcements
m
Why can't we create generic wrapper classes, like
class Wrapper<T> (val value: T) : T by value
?
d
Generics are erased, at runtime
T
just becomes
Any?
. And even if they weren't erased, the compiler would have to emit a new class for every
T
that's used, because superclasses cannot be dynamic on the JVM.
m
Delegation (replacing access with finction call) is done at compile time, not at runtime.
m
But you can't replace a function call at compile time when you don't know which functions you are going to replace yet.
m
? Sorry, I don't understand. Delegation just replaces
instance
with
instance.value
.
m
No, you are making
Wrapper
a subclass of
T
, which means that every public method in the class
T
will be inherited by
Wrapper
.
The delegation makes each of those overrided methods a call to the delegate.
So you can't do this when you don't know what the actual type
T
is.
m
We do know T at compile time.
wr: Wrapper<Int>(3); wr.coerceAtLeast(5)
should be just replaced by compiler with
wr.value.coerceAtLeast(5)
d
That's not how inheritance works.
m
Ok, is there any description how delegation inheritance work?
d
It's syntax sugar.
Copy code
interface Bar {
   fun barMethod(): String
}

class BarImpl : Bar {
   override fun barMethod() = "Hello from BarImpl"
}

class BarByDelegate(barImpl: BarImpl) : Bar by barImpl
// becomes:
class BarByDelegate(val barImpl: BarImpl) : Bar {
    override fun barMethod() = barImpl.barMethod()
}
BarByDelegate
implements
Bar
normally.
m
Ok, thanks. I missed (in documentation) that delegation is only for interfaces.
s
No higher kind types in Kotlin. You can inherit only from types in Kotlin (classes, interfaces that may or may not have generic type parameters), but you can't inherit from a generic type parameter (they get erased at runtime).