Johann Pardanaud
06/08/2023, 9:21 PMfun Any?.assertNotNull(): Unit = TODO()
val nullable: String? = ""
val nonNullable: String = ""
nullable.assertNotNull() // works
nonNullable.assertNotNull() // works too
The last line makes no sense because the value cannot be null
, but it compiles anyway. Is it possible to improve this?ephemient
06/08/2023, 9:29 PMString
can be transparently upcast into String?
, just like how all types can be safely upcast into one of their parentsephemient
06/08/2023, 9:30 PMfun Any?.assertNotNull(): Unit = TODO()
@Deprecated("Non-nullable type", level = DeprecationLevel.ERROR)
@JvmName("assertNotNull!")
fun Any.assertNotNull(): {
// no-op
}
Johann Pardanaud
06/08/2023, 9:32 PMGleb Minaev
06/09/2023, 7:43 AM@Suppress("INVISIBLE_REFERENCE", "INVISIBLE_MEMBER")
fun <T: Any> @kotlin.internal.Exact T?.assertNotNull(): T = this ?: TODO()
fun main() {
val nullable: String? = ""
val nonNullable: String = ""
nullable.assertNotNull() // works
nonNullable.assertNotNull() // does not compile
}
Johann Pardanaud
06/09/2023, 7:53 AM