Multiple type class

Trying to pass a class as 2 different types merged in a top-level parent. How to specify types correctly (not like a as B, needs a sure shot)?

class Foo<T>(foo: T) : Buz(foo = foo) {
    fun <T> bar(kyle: Kyle)
            where T : Chad,
                  T : Bar { = foo

class Buz(val foo: Chad)

class Kyle(var foo: Bar)

The variant is to create a common interface but it can be enormous for multiple combinations. What about where?

Iā€™m not sure if I understood you correctly, but I think you are describing intersection types. They are not available in kotlin yet, however there is syntax for it, you can use & to create intersection type with Any to force non-nullable version of a type, eg

fun <T> T.nonNull(): T & Any = this ?: throw NullPointerException()

And interesection types can be infered, you can see this syntax in IDEs eg. in Intellij IDEA when you enable inline hints and do something like this val foo = if(true) 1 else 0f you can see that infered type is Comparable<*> & Number, so I guess its the matter of time before intersection types will be implemented properly

1 Like

Suppose, something like this could solve the problem

val foo: Bar && Buz

Note that T cannot extend 2 classes at the same time, unless the classes extend each other, hence those classes should actually be interfaces.

interface Chad
interface Bar
class Foo<T>(val fooParam: T) : Buz(foo = fooParam) 
    where T : Chad, T: Bar
    fun bar(kyle: Kyle) { = fooParam

open class Buz(val foo: Chad)

class Kyle(var foo: Bar)

Yeah, I found the problem with the context scope and you need to override
class Foo<T>(override val foo: T) : Buz(foo = foo)