简体   繁体   English

如果没有隐式定义,如何返回None或引发异常?

[英]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. 我希望在使用时将不支持的对象发送到eval函数以返回None的情况下。 eg: 例如:

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

How can I do that ? 我怎样才能做到这一点 ?

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)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM