Is the Kotlin documentation written correctly?

Is the code correct (show below)? This was taken from Kotlin-docs.pdf page 63 which is also the last piece of code 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 as is, the compiler does not work: 1. One type argument expected for the interface. Comparable as defined in kotlin 2. Type inference error. 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 am still getting the following error: Cannot access "clone": it is protected in "Cloneable"

I am using Kotlin 1.1.2-release-IJ2017.1-1

Am I missing something? or is there a bug in the documentation?

Thank.

+3


source to share


1 answer


it.clone()

returns Any

and you get a list of forwarding errors to the list. So you changed it to List.

The following error Cannot access the clone: ​​it is protected in Cloneable .



This problem can be solved by creating our own Cloneable interface using a public method.

0


source







All Articles