Is the documentation correct?

Is the code (show below) correct? It was take from page 63 of the Kotlin-docs.pdf, which is also the last code snippet of https://kotlinlang.org/docs/reference/generics.html

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

Taken by as is, the compiler fails with:

  1. One type argument expected for interface Comparable defined in kotlin
  2. Type inference failed. Expected type mismatch: inferred type is List but List was expected
  3. Cannot access ‘clone’: it is protected in ‘Cloneable’

The first two errors are easily resolved by changing the code to the following:

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

I still get the following error:
Cannot access ‘clone’: it is protected in ‘Cloneable’

I’m using Kotlin 1.1.2-release-IJ2017.1-1

Am I missing something? or is there an error in the documentation?

Thanks.

Definitely seems to be an error.

There are 2 problems with that code that you found:

  • The need to specify type parameter on Comparable (note you do not need to add the “in”)
  • Java’s clone is protected

The code was revised in the current version to make the result List which adds another error:

  • If you were to be able to clone you would then need to cast to T which is not a problem in your example since you have List

I think the point of the example was about multiple where clauses not about cloning, but the code in the reference should be correct.

The cloneable issue was discussed here, but did not solve the problem:

Apparentlhy clone is not supported in Kotlin?

Thanks for responding Dale, and for providing clarity.

Cheers,

h