使用来自 Kotlin 的 Guava 的 toImmutableSortedMap 收集器的泛型错误

Generics errors using Guava's toImmutableSortedMap collector from Kotlin

我正在尝试使用来自 Kotlin 1.3.50 的 Guava toImmutableSortedMap 收集器(在 Java 13 on macOS 10.14.6 + 更新上)。每当我尝试使用 toImmutableSortedMap 时都会出现泛型错误,但如果我改用 toImmutableMap 则不会出现任何错误:

val map = mutableMapOf<String, MutableMap<Path, String>>()

// populate map

// toImmutableSortedMap has compile-time generics errors
map.entries.stream()
.collect(
    toImmutableSortedMap<Map.Entry<String, MutableMap<Path, String>>, String, ImmutableSortedMap<Path, String>>(
        naturalOrder<String>(),
        {it.key},                             // errors e1 & e2 here
        {ImmutableSortedMap.copyOf(it.value)} // errors e3 & e4 here
    )
)

// toImmutableMap works fine
map.entries.stream()
.collect(
    toImmutableMap<Map.Entry<String, MutableMap<Path, String>>, String, ImmutableSortedMap<Path, String>>(
        {it.key},
        {ImmutableSortedMap.copyOf(it.value)}
    )
)

toImmutableSortedMap 的泛型错误:

e1: Type mismatch: inferred type is () -> [ERROR : <ERROR PROPERTY TYPE>] but Function<in Map.Entry<String, MutableMap<Path, String>>!, out String!>! was expected
e2: Unresolved reference: it
e3: Type mismatch: inferred type is () -> ??? but Function<in Map.Entry<String, MutableMap<Path, String>>!, out ImmutableSortedMap<Path, String>!>! was expected
e4: Unresolved reference: it

有什么解决办法吗?

您可以显式添加一些类型,它会起作用:

map.entries.stream()
    .collect(
        toImmutableSortedMap<Map.Entry<String, MutableMap<Path, String>>, String, ImmutableSortedMap<Path, String>>(
            naturalOrder<String>(),
            Function { it.key },                             
            Function { ImmutableSortedMap.copyOf(it.value) } 
        )
    )

对我来说,Kotlin 中的 SAM 转换似乎有些问题