I have a function that looks something like:
fun MyInput?.toOutput() : Output? {
if (this == null) return null
return Output(this.someValue)
}
In places where I know that my MyInput
is non-null (for example, inside a method that takes a input: MyInput
as an arg), I'd like to be able to use input.toOutput
as Output
instead of Output?
I've tried using
contract {
returnsNotNull() implies (this@toOutput != null)
}
But that has the implication backwards. That tells me that if toOutput
returns a non-null type, that my input
was non-null. I want to tell the analyzer things about the return value based on the arguments. In Java, I could use org.jetbrains.annotations.@Contract("null -> null ; !null -> !null")
to accomplish this.
Is there a way to do this in Kotlin?
MyInput?.toOutput()
at all. Just provideMyInput.toOutput()
, and then let callers writemyInput?.toOutput()
with the question mark. That'll make the nullability behavior much more obvious to users as well as letting you avoid this entire issue. – EvangelicaltoOutput
from Java? – Lumbago