In javascript, we can do something like:
value = f1() || f2() || f3();
this will call f1, and assign it to value if the result is not null. only if the result is null, it will call f2, and assign it to value if that is not null. ...
A way to achieve this in scala is given here: How to make this first-not-null-result function more elegant/concise? create a getFirstNNWithOption function that calls each function until not null:
value = getFirstNNWithOption(List(f1 _, f2 _, f3 _))
However, this is not as nice as the javascript || operator, which is more flexible. eg:
value = f1() || f2(3) || f3(44, 'ddd') || value4;
is there a way to achieve this in scala?
=> is syntactic sugar for creating instances of functions. Recall that every function in scala is an instance of a class. For example, the type Int => String , is equivalent to the type Function1[Int,String] i.e. a function that takes an argument of type Int and returns a String .
On Scala Collections there is usually :+ and +: . Both add an element to the collection. :+ appends +: prepends. A good reminder is, : is where the Collection goes. There is as well colA ++: colB to concat collections, where the : side collection determines the resulting type.
Arrow is a type class for modeling composable relationships between two types. One example of such a composable relationship is function A => B ; other examples include cats. data. Kleisli (wrapping an A => F[B] , also known as ReaderT ), and cats.
Divide and Assignment Operator (/=) Divide And Assignment Scala Operator divides the first operand by the second, and then assigns the result to the left operand.
Since your are using function returning Option
.
The best solution would be to use Chaining Option like it is explained here Option's chaining
So you would do
f1().orElse(f2()).orElse(f3()).orElse(Some(4))
I am using the recommended Option
instead of null
.
For example:
class OptionPimp[T](o: Option[T]) {
def ||(opt: => Option[T]) = o orElse opt
def ||(t: => T) = o getOrElse t
}
implicit def optionPimp[T](o: Option[T]) = new OptionPimp(o)
def f1(): Option[Int] = None
def f2(): Option[Int] = None
def f3(): Option[Int] = Some(3)
val value1 = f1() || f2() || f3() || 4 // yields 3
val value2 = f1() || f2() || 4 // yields 4
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With