How to write a method that is generic across any n

2019-09-01 10:54发布

问题:

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?

回答1:

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 = ???