Scala Option implicit conversion - Bad practice or missing feature?

后端 未结 3 1211
面向向阳花
面向向阳花 2021-01-22 18:16

I represented my data model as case classes typing values that may be null as Option.

case class Document(id: Long, title: String, subtitle: Option[String])
         


        
3条回答
  •  既然无缘
    2021-01-22 18:22

    This can cause untold number of problems. The issue here isn't what you might think but what you don't think could happen. That is, if you make another implicit class that works on Option types you could wind up creating artificial results that you never intended to happen, i.e. operators for your overloaded types being present in your non-overloaded types.

     implicit class OptDouble(opt: Option[Double]) extends Any{
       def *(x: Double) = Some((opt getOrElse 0.0) * x)
       def ^(x: Double) = Some(Math.power(opt getOrElse 1.0, x))
     }
    
     val z = q^4.5
    

    The type of z is Option[Double]. You wouldn't expect that to happen but first Scala did an implicit conversion to Option and then it used the implicit class to call the ^ operator. Now people looking at your code are going to be scratching their heads wondering why they have an Option. You might start seeing a few defensive x getOrElse 0.0 sprinkled around the code as people fight to keep Option away (and yes, this is from personal experience.)

    That said, what you should do is use another apply on the object:

    object Document{
      def apply(id: Long, title: String, subtitle: String) = new Document(id, title, Some(subtitle))
    }
    

    which will do everything you wanted it to do as long as you don't have a default defined for subtitle, i.e. subtitle: Option[String] = None.

提交回复
热议问题