How to check for null or false in Scala concisely?

后端 未结 7 1538
时光取名叫无心
时光取名叫无心 2020-12-24 06:23

In Groovy language, it is very simple to check for null or false like:

groovy code:

def some = getSomething()
if(some) {
//         


        
7条回答
  •  無奈伤痛
    2020-12-24 06:54

    What you ask for is something in the line of Safe Navigation Operator (?.) of Groovy, andand gem of Ruby, or accessor variant of the existential operator (?.) of CoffeeScript. For such cases, I generally use ? method of my RichOption[T], which is defined as follows

    class RichOption[T](option: Option[T]) {
      def ?[V](f: T => Option[V]): Option[V] = option match {
        case Some(v) => f(v)
        case _ => None
      }
    }
    
    implicit def option2RichOption[T](option: Option[T]): RichOption[T] =
      new RichOption[T](option)
    

    and used as follows

    scala> val xs = None
    xs: None.type = None
    
    scala> xs.?(_ => Option("gotcha"))
    res1: Option[java.lang.String] = None
    
    scala> val ys = Some(1)
    ys: Some[Int] = Some(1)
    
    scala> ys.?(x => Some(x * 2))
    res2: Option[Int] = Some(2)
    

提交回复
热议问题