Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a proper null-safe coalescing operator in scala?

Tags:

Having seen the answers coming out of questions like this one involving horror shows like trying to catch the NPE and dredge the mangled name out of the stack trace, I am asking this question so I can answer it.

Comments or further improvements welcome.

like image 788
psp Avatar asked Sep 01 '09 20:09

psp


People also ask

Which is null coalescing operator?

The nullish coalescing operator ( ?? ) is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined , and otherwise returns its left-hand side operand.

Why we use null coalescing operator?

operator is known as Null-coalescing operator. It will return the value of its left-hand operand if it is not null. If it is null, then it will evaluate the right-hand operand and returns its result. Or if the left-hand operand evaluates to non-null, then it does not evaluate its right-hand operand.

Is coalesce null?

The COALESCE function returns NULL if all arguments are NULL . The following statement returns 1 because 1 is the first non-NULL argument. The following statement returns Not NULL because it is the first string argument that does not evaluate to NULL . you will get the division by zero error.

Is Nullish undefined?

A nullish value is a value that is either null or undefined .


1 Answers

Like so:

case class ?:[T](x: T) {   def apply(): T = x   def apply[U >: Null](f: T => U): ?:[U] =     if (x == null) ?:[U](null)     else ?:[U](f(x)) } 

And in action:

scala> val x = ?:("hel")(_ + "lo ")(_ * 2)(_ + "world")() x: java.lang.String = hello hello world  scala> val x = ?:("hel")(_ + "lo ")(_ => (null: String))(_ + "world")() x: java.lang.String = null 
like image 118
psp Avatar answered Oct 27 '22 05:10

psp