tsjnsn
tsjnsn

Reputation: 451

Is there a way to have this done implicitly?

Is there any way to have this implicit method called on x before it matches to meet the type requirements of the match?

If I call it directly it works as expected, but I would like to know if it's possible for the call to be inferred.

object ImplicitTest extends App {
  implicit def denull[T<:Any](mightBeNull:T):Option[T] = {
    if (mightBeNull == null) None
    else Some(canBeNull)
  }

  var x:String = null
  x match {  //works if i do "denull(x) match {"
    case Some(str:String) =>
      println(str)
    case None => None
  }
}

Upvotes: 1

Views: 123

Answers (2)

4lex1v
4lex1v

Reputation: 21557

You can wrap this with method which uses implicit convertion if you want:

def print[A](opt: Option[A]) = opt.foreach(println)

When you call this method on variable with null value, Scala compiler resolves your implicit convertion method denull, and if it isn't None, will print it. But you can simply do this without denull method:

var str: String = null
Option(str).foreach(println)

Scala won't resolve implicit conversion in pattern matching, because has no idea that it needs to be converted to some other type. Such way of conversion is a mechanism against type errors, when compiler can do "the last try" and use some value with type A in place where type B needed. In pattern matching you just match against type or other things

Upvotes: 1

drexin
drexin

Reputation: 24403

Instead of your denull method you should use Option.apply. It does the same thing. Possible null values should always be handled explicitly! Implicit conversion is dangerous and can be confusing for other people who have to work with your code. Do it like this:

Option(x) match {}

or in most cases even better:

Option(x).fold { ... } { ... }

Upvotes: 6

Related Questions