hoang
11/23/2020, 10:57 AMkotlin 1.4.20
and Optional<V>
Type mismatch: inferred type is Optional<V!!> but Optional<V> was expected
the same code compile ok in kotlin 1.4.10
fun first(vPredicate: (V) -> Boolean): Optional<V> {
val v: V? = firstOrNull(vPredicate)
return if (v == null) {
Optional.empty()
} else {
Optional.of(v)
}
}
the errored line is the one that return Optional.empty()
Victor Petukhov
11/23/2020, 12:38 PMV
and firstOrNull
.
I couldn’t reproduce it with the following example:
import java.util.*
fun <V> first(vPredicate: (V) -> Boolean): Optional<V> {
val v: V? = null
return if (v == null) {
Optional.empty()
} else {
Optional.of(v)
}
}
hoang
11/23/2020, 2:47 PMimport java.util.*
import java.util.concurrent.ConcurrentHashMap
abstract class BaseCache2<K, V> {
private val cache = ConcurrentHashMap<K, V>()
fun firstOrNull(vPredicate: (V) -> Boolean): V? = cache.values.firstOrNull(vPredicate)
fun first(vPredicate: (V) -> Boolean): Optional<V> {
val v: V? = firstOrNull(vPredicate)
return if (v == null) {
Optional.empty()
} else {
Optional.of(v)
}
}
}
hoang
11/23/2020, 2:52 PMOptional.empty()
in place of generics Optional<V>
is enough to cause compile error:
abstract class GenericsOverV<V> {
fun justEmpty(): Optional<V> {
return Optional.empty()
}
}