I'm using Kotlin
and thought about writing universal method to check if any of passed arguments are not null
.
Method could be used in if
statement instead manually checking each argument. And if parameters are not null then compiler should assume that inside if
statement they are still not null
. Example below:
fun getFoo(): Foo? {
//return value
}
fun getBar(): Bar? {
//return value
}
fun execute(foo: Foo, bar: Bar) {
//do stuff
}
This is "traditional" way:
val foo = getFoo()
val bar = getBar()
if(foo != null && bar != null) {
execute(foo, bar)
}
And this is what I thought to do:
fun isNotNull(vararg params: Any?): Boolean {
return params.filterNotNull().isNotEmpty()
}
val foo = getFoo()
val bar = getBar()
if(isNotNull(foo, bar)) {
execute(foo, bar)
}
Of course code above is not compiling (Type mismatch, Required: Foo, Found: Foo?
).
Is there any way to assure compiler that foo
and bar
was already checked for null
? I could use !!
in each parameter but it's not very elegant solution. Maybe some construction using contract
?
When using manual check foo != null && bar != null
then there is not problem because of automatic smart cast
to Foo
and Bar
.