igx
igx

Reputation: 4231

How can I return None or throw an exception if no implicit defined?

I have this function:

case object Evaluator {
    import Ordering.Implicits._
    def eval[T: Ordering](x: T, y: T): Boolean = Some(x < y)
}

I want that in case that the use sends unsupported object to the eval function to return None. e.g.:

case object Bar
assert(Evaluator.eval(Bar, 1) == None)

How can I do that ?

Upvotes: 1

Views: 98

Answers (1)

Arseniy Zhizhelev
Arseniy Zhizhelev

Reputation: 2401

Try providing the default value for the implicit argument.

case object Evaluator{
    import Ordering.Implicits._
    def eval[T](x: T, y: T)(implicit ev:Ordering[T] = null):Boolan =
      if(ev == null)
        None 
      else
        Some(x < y)
}

Upvotes: 4

Related Questions