``不能解决Scala中符号'错误的泛型方法 [英] Generic method with `cannot resolve symbol` errors in Scala

查看:162
本文介绍了``不能解决Scala中符号'错误的泛型方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



check [Int](10,1,5)

我需要一个通用检查方法, and check [Double](10.0,1.0,5.0)



这个代码:

  trait RangeChecker {
def check [T (值> =迷你&&值< =最大)
}
}

然而,当> =>时,得到无法解析符号 && <=
什么可能是错误的?



 

解决方案

def check [T<:AnyVal] ...

定义 all AnyVal 的子类型的方法。
然而,你的实现使用了两个只能用的方法(< = > = )对于类型的子集,即支持排序的类型。



因此,您必须指定该方法适用于所有类型,订购存在,或者换句话说

  def check [T](value:T,min: T,max:T)(隐式ev:T => Ordered [T]):Boolean = 
value> = min&&值<=最大

此语法等同于视图界限(< ;%

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

但自视图范围已被弃用,您应该避免它。





另一种选择是以这种方式使用 Ordering



<$ (隐式ord:排序[T]):布尔= {
import ord.mkOrderingOps
值> =迷你&&值< = maxi
}

其中 ord.mkOrderingOps 可让您使用常规> = <= 方法。



直接使用上下文绑定的另一个等效替代选项:

  def check [T:Ordering](value:T,mini:T,maxi:T):布尔= {
val ord =隐式[Ordering [T]]
import ord.mkOrderingOps
value> ; =迷你&&值<=最大
}


I need to get a generic check method that can be used as follows:

check[Int](10, 1, 5) and check[Double](10.0, 1.0, 5.0).

I tried this code:

trait RangeChecker {
  def check[T <: AnyVal](value:T, mini:T, maxi:T) : Boolean = {
    (value >= mini && value <= maxi)
  }
}

However, I get Cannot resolve symbol errors for >=, && and <=. What might be wrong?

解决方案

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
}

这篇关于``不能解决Scala中符号'错误的泛型方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆