Let's imagine you have 2 fonctions returning nullable and you cant to compose this 2 functions :
fun giveInt(x: Int):Int? = x+1
fun giveInt2(x: Int):Int? = x+2
To achieve the composition, I wrote this functions :
fun all(x:Int):Int? {
val y = giveInt(x)
if (y != null) return giveInt2(y) else return null;
}
val four = all(1)
Is it possible to compose 2 nullable values to get another nullable without explicitly writing if (y != null)
and return null
?
In Scala I would just do something like :
def giveInt(x: Int):Option[Int] = Some(x+1)
def giveInt2(x: Int):Option[Int] = Some(x+2)
def all(x:Int): Option[Int] = giveInt(x).flatMap(giveInt2)
Should I use java Optional to achieve this or is it possible with ?
operator?
Thanks :)