我认为您在这里混淆了(参考您的评论)...Collection<out T>
会以与Array<out T>
. 在这种情况下,T
可以通过任何方式(即T : Any?
)...一旦您将 设置T
为String
,您基本上是在使用您的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()
最后,您的问题的解决方案可以是以下之一(取决于您真正需要的):
fun <T : String?> f4a(c: MutableCollection<out T>): MutableCollection<out T> = TODO()
fun <C : MutableCollection<out String?>> f4b(c: C): C = TODO()