Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 Some, e.g. Some(5). What about something like this:

implicit def T2OptionT( x : T) : Option[T] = if ( x == null ) None else Some(x) 
like image 963
Alex Black Avatar asked Nov 17 '09 03:11

Alex Black


People also ask

What is implicit conversion in Scala?

Implicit conversions in Scala are the set of methods that are apply when an object of wrong type is used. It allows the compiler to automatically convert of one type to another. Implicit conversions are applied in two conditions: First, if an expression of type A and S does not match to the expected expression type B.

What is implicit conversions?

An implicit conversion sequence is the sequence of conversions required to convert an argument in a function call to the type of the corresponding parameter in a function declaration. The compiler tries to determine an implicit conversion sequence for each argument.


2 Answers

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.

like image 195
Mitch Blevins Avatar answered Oct 06 '22 17:10

Mitch Blevins


Note that you could use the explicit implicit pattern which would avoid confusion and keep code terse at the same time.

What I mean by explicit implicit is rather than have a direct conversion from T to Option[T] you could have a conversion to a wrapper object which provides the means to do the conversion from T to Option[T].

class Optionable[T <: AnyRef](value: T) {   def toOption: Option[T] = if ( value == null ) None else Some(value) }  implicit def anyRefToOptionable[T <: AnyRef](value: T) = new Optionable(value) 

... I might find a better name for it than Optionable, but now you can write code like:

val x: String = "foo" x.toOption // Some("foo")  val y: String = null x.toOption // None 

I believe that this way is fully transparent and aids in the understanding of the written code - eliminating all checks for null in a nice way.

Note the T <: AnyRef - you should only do this implicit conversion for types that allow null values, which by definition are reference types.

like image 37
Flaviu Cipcigan Avatar answered Oct 06 '22 17:10

Flaviu Cipcigan