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])
Now I try to instantiate the case class:
Document(123, "The Title", "Subtitle") // Doesn't work
But NOPE! This doesn't work, I have to wrap the optional value in a Some.
Document(123, "The Title", Some("Subtitle")) // Works
Scala is very clever about types in general, but why is it not self-evident that a hard coded literal, or (any string for that matter) is a different than null/None?
I was able to fix this and make Scala "more clever" by adding this implicit conversion
implicit def autoSome[T](any:T) = Some(any)
Document(123, "The Title", "Subtitle") // Now it works!
Question: Am I the only one that the language should provide implicit conversion T -> Some(T) out of the box? Or is there any gotchas that I'm not aware of about having so broad implicit everywhere by default?
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.The type of
z
isOption[Double]
. You wouldn't expect that to happen but first Scala did an implicit conversion toOption
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 anOption
. You might start seeing a few defensivex getOrElse 0.0
sprinkled around the code as people fight to keepOption
away (and yes, this is from personal experience.)That said, what you should do is use another
apply
on the object: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: