Kotlin generics

2019-04-18 15:36发布

问题:

How is it possible to enforce a generic type for a method in Kotlin? I know for instance you can do the following:

var someVar: MutableSet<out SomeType> = hashSetOf()

How can you do the same for a method?

fun <T> doSomething() {
}

I'd like to enforce T to be of type X or a sub-type of it.

Thanks.

回答1:

After googling around, the correct answer would be:

fun <T : X> doSomething() {
}


回答2:

Actually out SomeType means more than "type Parameter can be SomeType or any of its subtypes" as your questions suggests.

The keyword out is Kotlin's way to say that, in this example, the MutableSet is a Producer of SomeType, i.e. it is covariant in its type parameter. As a consequence you will not be able to call methods like add(t:T), but only those which return Ts, like get():T.

Back to your question: if your method is supposed to accept types of X or its subtypes, you should use "bounds":

fun <T : X> doSomething() {
}

This is just what you need, but to make it clear again, it cannot be said to be the equivalent to your other example.



回答3:

as @s1m0nw1 quoted, you can use fun <T : X> doSomething() { }

to limit T subtype of X,

additional, you can use fun <T> doSomething where T : Comparable, T : Cloneable { }

to limit T should implement both Comparable and Cloneable

as referenced here https://kotlinlang.org/docs/reference/generics.html