在Kotlin中是否可以编写一个可以用可空值集合和不可空值集合调用的函数?我在想这样的事情:
fun <C: MutableCollection<out String>> f(c: C): C {
// ...
}
我不需要这样写,因为我的返回值为C
类型。另外请注意out
关键字,但即使使用它也无法调用f(mutableListOf<String?>)
,但是f(mutableListOf<String>)
可以正常工作。我必须在这里更改什么,或者在Kotlin中这不可能吗?使用数组可以很好地工作...
答案 0 :(得分:2)
fun <C: MutableCollection<out String?>> f(c: C): C {
return c;
}
fun main(args: Array<String>) {
println(f(mutableListOf("hello")))
println(f(mutableListOf<String?>(null)))
}
答案 1 :(得分:1)
我认为您在这里混在一起(参考您的评论)... Collection<out T>
的工作方式与Array<out T>
相同。在这种情况下,T
可能会发生任何事情(即T : Any?
)……只要将T
设置为String
,基本上就是使用{{1 }},那么您必须使用非空类型...
虽然简短的答案是将C
添加到通用类型?
,即使用C
,但这里有一些更多的示例,可能有助于更好地理解它们如何共同发挥作用:
fun <C: MutableCollection<out String?>> f(c: C):C
最后,解决问题的方法可以是以下方法之一(取决于您的实际需求):
// your variant:
fun <C : MutableCollection<out String>> f1(c: C): C = TODO()
// given type must be non-nullable; returned one therefore contains too only non-nullable types
// your variant with just another generic type
fun <T : String, C : MutableCollection<out T>> f2(c: C): C = TODO()
// you have now your "out T", but it still accepts only non-nullable types (now it is probably just more visible as it is in front)
// previous variant adapted to allow nullable types:
fun <T : String?, C : MutableCollection<out T>> f3(c: C): C = TODO()