https://kotlinlang.org logo
#announcements
Title
# announcements
m

Maxim Kizub

10/24/2019, 12:33 PM
Why can't we create generic wrapper classes, like
class Wrapper<T> (val value: T) : T by value
?
d

diesieben07

10/24/2019, 12:37 PM
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

Maxim Kizub

10/24/2019, 1:02 PM
Delegation (replacing access with finction call) is done at compile time, not at runtime.
m

marstran

10/24/2019, 1:06 PM
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

Maxim Kizub

10/24/2019, 1:17 PM
? Sorry, I don't understand. Delegation just replaces
instance
with
instance.value
.
m

marstran

10/24/2019, 1:33 PM
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

Maxim Kizub

10/24/2019, 1:43 PM
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

diesieben07

10/24/2019, 1:48 PM
That's not how inheritance works.
m

Maxim Kizub

10/24/2019, 1:53 PM
Ok, is there any description how delegation inheritance work?
d

diesieben07

10/24/2019, 1:55 PM
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

Maxim Kizub

10/24/2019, 2:03 PM
Ok, thanks. I missed (in documentation) that delegation is only for interfaces.
s

streetsofboston

10/24/2019, 2:54 PM
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).
15 Views