hho
04/26/2023, 7:57 PMYoussef Shoaib [MOD]
04/26/2023, 8:00 PMfun foo(x: Type): ReturnType
fun foo(x: Nothing?): ReturnType?
Youssef Shoaib [MOD]
04/26/2023, 8:00 PMType?
instead of Nothing?
hho
04/26/2023, 8:14 PMephemient
04/26/2023, 8:27 PM@Contract("null -> null, !null -> !null")
which may be used by IDE inspections, but the Kotlin compiler doesn't make use of itephemient
04/26/2023, 8:29 PMkotlin.contracts
, you can write
@OptIn(ExperimentalContracts::class)
fun foo(x: T?): U? {
contract {
returnsNotNull() implies (x != null)
}
but that probably doesn't give you what you want ((x != null) implies returnsNotNull()
is not possible)ephemient
04/26/2023, 8:30 PMnull
, but not for values of nullable typeYoussef Shoaib [MOD]
04/26/2023, 8:31 PMType?
should therefore do the trickYoussef Shoaib [MOD]
04/26/2023, 8:32 PMephemient
04/26/2023, 8:32 PMhho
04/26/2023, 8:33 PMhho
04/26/2023, 8:33 PM@Contract
annotation, but with smartcasts as a result…Youssef Shoaib [MOD]
04/26/2023, 8:34 PM@JvmName("fooNotNull")
does the trick I believeephemient
04/26/2023, 8:35 PMfun foo(x: Any): Any { ... }
@JvmName("nullableFoo")
fun foo(x: Any?): Any? = if (x != null) foo(x) else null
since it's slightly easier to smart-cast to non-nullable to call the right overload, than it is to go the other way, but yeahYoussef Shoaib [MOD]
04/26/2023, 8:38 PM?.
when calling itephemient
04/26/2023, 8:40 PMephemient
04/26/2023, 8:41 PMfun foo(x: Any?): Any? { ... }
fun foo(x: Any): Any = foo(x as Any?)!!
is just plain uglier IMOhho
04/26/2023, 9:19 PMfun <T> newVariable(value: T?): Variable<T>? = value?.let { Variable(it, null, null) }
Youssef Shoaib [MOD]
04/27/2023, 12:19 AMfun main() {
val kotlin = "🙂"
println(newVariable(kotlin))
val nullableKotlin: String? = null
println(newVariable(nullableKotlin))
val nullableKotlin2: String? = kotlin
println(newVariable(nullableKotlin2))
}
data class Variable<T>(val value: T, val second: String?, val third: Int?)
@JvmName("newVariableNullable")
fun <T> newVariable(value: T?): Variable<T>? = value?.let { Variable<T>(it, null, null) }.also { print("nullable: ") }
fun <T: Any> newVariable(value: T): Variable<T> = Variable(value, null, null).also { print("non null: ") }
prints:
non null: Variable(value=🙂, second=null, third=null)
nullable: null
nullable: Variable(value=🙂, second=null, third=null)