Why map method can not infer the right type

I’m a beginner to Kotlin language. I come across a problem when I test the code snippet of the docs. It’s at “Class and Objects/Generic constraints/Upper bounds” section and written as follow:

fun <T> cloneWhenGreater(list: List<T>, threshold: T): List<T>
    where T : Comparable,
          T : Cloneable {
  return list.filter { it > threshold }.map { it.clone() }
}

I use Intellij IDEA to compile it but errors occure. It tips me “one type argument expected for interface Comparable define in Kotlin” at the “where T: Comparable” of the snippet, and “Type inference failed …” at the “.map { it.clone() }” of the snippet, it requires List, but finds the List .

I modify the first error by changing the Comparable to Comparable. But the second error I don’t know why the map method can not infer the type List ?

Thank you.

Because T.clone() returns Any and you get error casting List<Any> to List<T>.
Your next error will be Cannot access clone: it is protected in Cloneable .

2 Likes

Could you tell me how can I fix it ? Sorry,I find the <T> lost in the post, I forgot it’s md.

Object.clone() is not a method to clone an object (surprise!). That example in the docs is not compilable/useable by itself, it’s just a demo of how you can write things if you need two upper bound constraints. If you make your own Cloneable interface with public method, that example would work.

I see. Thank you for your time.