Alex Black Alex Black - 11 months ago 67
Scala Question

Could/should an implicit conversion from T to Option[T] be added/created in Scala?

Is this an opportunity to make things a bit more efficient (for the prorammer): I find it gets a bit tiresome having to wrap things in

, e.g.
. What about something like this:

implicit def T2OptionT( x : T) : Option[T] = if ( x == null ) None else Some(x)

Answer Source

You would lose some type safety and possibly cause confusion. For example:

  val iThinkThisIsAList = 2 
  for (i <- iThinkThisIsAList) yield { i + 1 }

I (for whatever reason) thought I had a list, and it didn't get caught by the compiler when I iterated over it because it was auto-converted to an Option[Int].

I should add that I think this is a great implicit to have explicitly imported, just probably not a global default.