Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

equivalent to the javascript operator || in scala

Tags:

scala

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?

like image 900
David Portabella Avatar asked Jan 04 '12 10:01

David Portabella


People also ask

What is the meaning of => 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 .

What does :+ mean in Scala?

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.

What does arrow mean in Scala?

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.

How do you do division in Scala?

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.


2 Answers

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))
like image 183
Andy Petrella Avatar answered Nov 15 '22 11:11

Andy Petrella


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
like image 40
Peter Schmitz Avatar answered Nov 15 '22 09:11

Peter Schmitz