Reputation: 942
I have a delegate interface:
interface Delegate {
fun didSelectWord(word: String)
}
And I would like to have a property called delegate
val delegate: <T> where T : Delegate
the delegate
can be anything that implements Delegate
I have also tried
val delegate: Any : Delegate
But both give compile error
Upvotes: 2
Views: 878
Reputation: 13865
You can do like this:
class SomeClass<T : Delegate> {
val delegate: T = // initialize delegate ...
}
Make the class
a generic type that declares the type parameter T
. And you can create properties of type T
.
Upvotes: 0
Reputation: 126624
The solution is pretty easy
val delegate: Delegate
Now something like this works
interface Delegate
class Test: Delegate {
fun yourMethod() = "Your Method"
}
fun test() {
val delegate: Delegate
delegate = Test()
println(delegate)
}
If you want to use a function that is only present in Test
, but not in Delegate
, you have to cast it
(delegate as Test).yourMethod()
Otherwise only functions that are present in Delegate
will work
delegate.yourMethod()
will not work.
Upvotes: 3