Anyone got an idea how to make this work? Basicall...
# getting-started
m
Anyone got an idea how to make this work? Basically the function’s type parameter
Interface
needs to be a supertype of the class’s type parameter
Implementation
.
Copy code
interface SomeInterface1
interface SomeInterface2
class SomeClass : SomeInterface1, SomeInterface2

class Component<Implementation> {

	fun <Interface> provides(): Component<Implementation>
		where Implementation : Interface // Implementation does not refer to a type parameter of provides
		= this
}

fun <T> component(): Component<T> = TODO()

fun main() {
	component<SomeClass>()
		.provides<SomeInterface1>()
		.provides<SomeInterface2>()
}
l
You can't constrain generics of a class inside its members, as it must be on declaration, like
Class<Interface, Implementation : Interface>
, or you have to check if
Interface
is the supertype of
Implementation
inside
provide
like this:
Copy code
fun <Interface> provide(): Interface? {
    return this as? Interface
}
y
You can perhaps declare it as an extension:
Copy code
interface SomeInterface1
interface SomeInterface2
class SomeClass : SomeInterface1, SomeInterface2

class Component<Implementation> {
}

fun <Interface, Implementation> Component<Implementation>.provides(): Component<Implementation>
		where Implementation : Interface
		= this

fun <T> component(): Component<T> = TODO()

fun main() {
	component<SomeClass>()
		.provides<SomeInterface1, _>()
		.provides<SomeInterface2, _>()
}
It's a little more clunky on the use-side, but it does compile!