This is not best practice or something else, but here you can do something similar:
scala> implicit class RubyFriend[T](val value: Option[T]) extends AnyVal {
| def ||=(alt: T): Option[T] = value orElse Some(alt)
| }
defined class RubyFriend
scala> var something: Option[Int] = None
something: Option[Int] = None
scala> something = something ||= 5
something: Option[Int] = Some(5)
scala> something ||= 4
res11: Option[Int] = Some(5)
scala> (None: Option[Int]) ||= 3
res12: Option[Int] = Some(3)
We create an implicit conversion from Optionto RubyFriendthat has a method ||=. This is the pimp of my library. The only difference that it cannot really assign to the original variable, because in Scala the assignment cannot be overloaded, as far as I know.
In general, try to avoid vars in Scala.
:
scala> import scala.language.implicitConversions
import scala.language.implicitConversions
scala> implicit class RubyFriend[T](var value: Option[T]) {
| def ||=(alt: T): Unit = value = value orElse Some(alt)
| }
defined class RubyFriend
scala> implicit def ruby2Option[T](smth: RubyFriend[T]): Option[T] = smth.value
ruby2Option: [T](smth: RubyFriend[T])Option[T]
scala> var ropt: RubyFriend[Int] = None
ropt: RubyFriend[Int] = RubyFriend@2d483fef
scala> ropt.value
res0: Option[Int] = None
scala> val opt: Option[Int] = ropt
opt: Option[Int] = None
scala> ropt ||= 6
scala> ropt.value
res2: Option[Int] = Some(6)
scala> val opt: Option[Int] = ropt
opt: Option[Int] = Some(6)
scala> ropt ||= 7
scala> ropt.value
res4: Option[Int] = Some(6)
Option . (yikes).
- , Scala :).
"" , @senia:
scala> implicit class RubyFriend[T](val value: Option[T]) extends AnyVal {
| def ||(alt: T): Option[T] = value orElse Some(alt)
| }
defined class RubyFriend
scala> var something: Option[Int] = None
something: Option[Int] = None
scala> something ||= 5
scala> something
res1: Option[Int] = Some(5)
scala> something ||= 6
scala> something
res3: Option[Int] = Some(5)