Scala Option implicit conversion - Bad practice or missing feature?

淺唱寂寞╮ 提交于 2019-12-02 02:37:41

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.

Most problems pointed out earlier can easily be fixed with a small change to the implicit: implict def autoOpt[T](x: T): Option[T] = Option(x)

I can't really think of a good reason scala does not provide this conversion as a part of the default library of implicit converters.

The fact that implicts make code harder to understand can be used as an argument against using any implicit, but not as one against using this particular one

That's a pretty dangerous implementation:

scala> val s: String = null
s: String = null

scala> Document(123, "The Title", s)
res2: Document = Document(123,The Title,Some(null))
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!