hello, anyone has fail compile issue with the new ...
# announcements
h
hello, anyone has fail compile issue with the new
kotlin 1.4.20
and
Optional<V>
Copy code
Type mismatch: inferred type is Optional<V!!> but Optional<V> was expected
the same code compile ok in
kotlin 1.4.10
Copy code
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()
v
Could you provide self-contained example? Here there is no declaration of
V
and
firstOrNull
. I couldn’t reproduce it with the following example:
Copy code
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)
    }
}
h
This is the self-contained code:
Copy code
import 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)
        }
    }
}
well, even just return
Optional.empty()
in place of generics
Optional<V>
is enough to cause compile error:
Copy code
abstract class GenericsOverV<V> {
    fun justEmpty(): Optional<V> {
        return Optional.empty()
    }
}