Curious to hear everyones thoughts. I wanted to ex...
# language-proposals
m
Curious to hear everyones thoughts. I wanted to expand on class delegation to also work with a
List
of some type. For example:
Copy code
interface Base {
    fun print()
}

class BaseImpl(val x: Int) : Base {
    override fun print() { print(x) }
}

class Derived(val b: List<Base>) : Base by b
// or maybe use varargs
class Derived(vararg val b: Base) : Base by b
The
Derived
class would just iterate over the list and invoke whatever is being overridden. This is really useful in scenarios when you can only register a single instance as a callback to something
g
I think it’s too specific use case for language feature> You probably just could solve it by implementing manyual implementation of it:
Copy code
class IterableBase(val instances: List<Base>) : Base {
    override fun print() { instances.forEach( print() }
}

class Derived(val b: List<Base>) : Base by IterableBase(b)
Of course, it’s manual implementation, but I really don’t think it would be very helpful language feature
d
It also falls apart as soon as you have a return type other than
Unit
1
👍 1
m
I wouldn't say it falls apart. The conflict can be resolved with some manual intervention.
g
And how it would look like?
m
Essentially Kotlin can generate the non ambiguous implementations, eg everything that returns
Unit
. For all others you have to manually implement the method. So:
Copy code
interface Base {
    fun print()
    fun foo(): String
}

class BaseImpl1(val x: Int) : Base {
    override fun print() { print(x) }
    override fun foo() = "1"
}

class BaseImpl2(val x: Int) : Base {
    override fun print() { print(x) }
    override fun foo() = "2"
}

class Derived(vararg val delegates: Base) : Base by delegates {
    override fun foo(): String {
        // Manually implement some logic
        return delegates.map { it.foo() }.joinToString()
    }
}
g
Ehh, extremely strange case, where you forced to provide implementation
m
That is no different than how you would resolve conflicting
interface
implementations on a single class
g
In a single class you add some behavior if you want (it's not a conflict), but with multiple classes you forced to do that, so this multidelegation works only for methods with Unit return type, so it makes it very special case