Kotlin平台types和generics

我被困在最后一个Kotlin Koans任务28中,当我尝试调用partitionTo函数时,得到这些错误消息:

Error:(25, 12) Kotlin: Type inference failed. Expected type mismatch: found: kotlin.Pair<kotlin.Collection, kotlin.Collection> required: kotlin.Pair<kotlin.List, kotlin.List> Error:(30, 12) Kotlin: Type inference failed. Expected type mismatch: found: kotlin.Pair<kotlin.Collection, kotlin.Collection> required: kotlin.Pair<kotlin.Set, kotlin.Set> 

我读了一个types末尾的感叹号标记了一个平台types。 但后来我会期待java.lang.String!typesjava.lang.String! 而不是kotlin.String! 。 我必须在某处强制执行空检查吗? 也许有人可以帮我完成最后一项任务。 我正在使用IntelliJs Kotlin插件版本0.10.195。

这是我的代码:

 fun List.partitionWordsAndLines(): Pair<List, List> { return partitionTo(ArrayList(), ArrayList()) { s -> !s.contains(" ") } } fun Set.partitionLettersAndOtherSymbols(): Pair<Set, Set> { return partitionTo(HashSet(), HashSet()) { c -> c in 'a'..'z' || c in 'A'..'Z'} } inline fun  Collection.partitionTo(first: MutableCollection, second: MutableCollection, predicate: (T) -> Boolean): Pair<Collection, Collection> { for (element in this) { if (predicate(element)) { first.add(element) } else { second.add(element) } } return Pair(first, second) } 

问题是你答应要返回一对List s:

 fun List.partitionWordsAndLines(): Pair, List> { 

但实际上还是返回了一对Collection

 inline fun  Collection.partitionTo(...): Pair, Collection> { 

来自任务的有用提示:

  The signature of the function 'toCollection()' from standard library may help you. 

在这里看到: https : //github.com/JetBrains/kotlin/blob/master/libraries/stdlib/src/generated/_Snapshots.kt#L207

PS为什么你要使用inline和通过partitionTo

检查你返回的typespartitionWordsAndLines(): **Pair, List>** ,扩展需要List或者Set where partitionTo返回Collection

这里是固定版本

inline fun > Collection.partitionTo(first: C, second: C, predicate: (T) -> Boolean): Pair