Kotlin 1.6.20 has been released. Highlights inclu...
# announcements
a
Kotlin 1.6.20 has been released. Highlights include: • Prototype of context receivers on JVM • Definitely non-nullable types • Performance improvements for JVM, Native, and JS • Hierarchical structure support for multiplatform projects Read more in the blog post.
🎉 129
😀 10
👍 10
👍🏻 1
🦜 46
💯 5
K 145
🙌 4
🚀 40
K 52
🐕 12
n
I get the warning "type mismatch: value of a nullable type Optional<T> is used where non-nullable type is expected." in my code when compiling with 1.6.20 which I did not get with 1.6.10. Test code which will produce the same warning is:
Copy code
fun <T> getTest(): Optional<T> { return Optional.empty() }
What is the actual issue here and how can I fix my code to avoid this warning? BTW: even
fun <T> getEmpty2(): Optional<T> = Optional.empty<T>()
produces the same warning, but
fun <T> getList2(): List<T> = emptyList<T>()
does not
g
It’s not the best place to report issues
👍🏻 2
👍 1
a
d
The issue is that
Optional.empty
returns
Optional<T & Any>
, i.e. its type argument is strictly not nullable and when it’s used as return expression for
Optional<T>
we’ve got type mismatch The simplest (and probably the most expected) workaround is adding an upper bound to
T
Copy code
fun <T : Any> getTest(): Optional<T> = Optional.empty<T>()
Another option is using definitely not nullable types
Copy code
fun <T> getTest(): Optional<T & Any> = Optional.empty<T>()
👍 4