views:

219

answers:

1

@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?

+6  A: 

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.

Daniel
Oh Gosh! You'r right! Page 223 in O'Reilly Programming Scala. Thanks!
paulosuzart