本文介绍了如何编写一个在scala中通过任意数字(Ordering [_])通用的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图实现一个可应用于任何数字的简单方法:
调用上述(或者我用 _ $替换 A c $ c>)给了我以下错误:
error:type mismatch;
found:Int(3)
required:Ordering [_]
NumberUtils.bucketise(List(1,2,3),3)
什么是我想要达到的正确语法?
解决方案
def bucketise [A](存储桶:Seq [A ],候选人:A)(隐式ev:排序[A]):A = ???
可以以加糖形式写入:
def bucketise [A:排序](桶:Seq [A],候选人:A):A = ???
I'm trying to implement a simple method that can be applied to any number:
/** * Round `candidate` to the nearest `bucket` value. */ def bucketise[Ordering[A]](buckets: Seq[Ordering[A]], candidate: Ordering[A]): Ordering[A] = ???I don't want just parameterise totally generically since my method will use < and > comparisons. I think that means I should restrict to any Ordering[_] type, but I don't seem to be able to specify that.
Calling the above (or the variation where I replace A with _) gives me the following error:
error: type mismatch; found : Int(3) required: Ordering[_] NumberUtils.bucketise(List(1,2,3), 3)What's the right syntax for what I'm trying to achieve?
解决方案Unless I misunderstand, what you want is:
def bucketise[A](buckets: Seq[A], candidate: A)(implicit ev: Ordering[A]): A = ???which can be written in the sugared form:
def bucketise[A : Ordering](buckets: Seq[A], candidate: A): A = ???
这篇关于如何编写一个在scala中通过任意数字(Ordering [_])通用的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
10-27 15:07