Question

@lucastex posted about the Java Elvis operator, and I tried something in Scala to get the same effect.

I've just converted everything to a new Structural Type with the ?: operator taking an object of the same type as argument. So Say:

implicit def toRockStar[B](v : B) = new { 
                            def ?:(opt: => B) = if (v == null) opt else v}
val name: String = "Paulo" // example

Why name ?: "Lucas" gets "Lucas" and name.?:{"Lucas"} gets Paulo? The new Structural Type is supposed to return the initial value of anything if it is not null, that is, "Paulo" in the above code.

I'm a bit confused. Any explanation?

Was it helpful?

Solution

Your operator ends in :, which means it reads right to left when in infix notation. For example:

scala> 1 :: Nil == Nil.::(1)
res2: Boolean = true

All methods read left to right in dot notation, though. So you are actually applying your method to Lucas in the infix notation, and to name in the dot notation.

By the way, the Elvis operator was not accepted for inclusion in Java 7.

OTHER TIPS

For the record (finding this thread while searching back the following article...), Daniel Spiewak (another famous Daniel in the Scala world...) posted an article about Implementing Groovy’s Elvis Operator in Scala.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top