且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

``不能解决Scala中符号'错误的泛型方法

更新时间:2023-12-04 15:50:52

When you write

def check[T <: AnyVal] ...

you're defining the method for all the subtypes of AnyVal. However, your implementation uses two methods (<= and >=) which are available only for a subset of types, namely the ones that support ordering.

So you have to specify that the method applies to all types for which an ordering exists, or in other words

def check[T](value: T, min: T, max: T)(implicit ev: T => Ordered[T]): Boolean =
  value >= min && value <= max

This syntax is equivalent to a view bound (<%)

def check[T <% Ordered[T]](value: T, min: T, max: T): Boolean = ...

but, since view bounds are deprecated, you should avoid it.


Another option is to use Ordering in this fashion

def check[T](value: T, mini: T, maxi: T)(implicit ord: Ordering[T]): Boolean = {
  import ord.mkOrderingOps
  value >= mini && value <= maxi
}

where importing ord.mkOrderingOps gives you the ability of using the regular >= and <= methods.

Another equivalent alternative using a context bound directly:

def check[T: Ordering](value: T, mini: T, maxi: T): Boolean = {
  val ord = implicitly[Ordering[T]]
  import ord.mkOrderingOps
  value >= mini && value <= maxi
}

相关阅读

推荐文章