In scala, we can use implicit typeclasses to conditionally add methods to a parameterized type, depending on the parameters of this type. For example, Iterator.sum :
def sum[B >: A](implicit num: Numeric[B]): B = foldLeft(num.zero)(num.plus)
For this method, there must be an instance of the Numeric class for this method:
scala> List(1, 2, 3).sum res0: Int = 6 scala> List("a", "b").sum <console>:6: error: could not find implicit value for parameter num: Numeric[java.lang.String] List("a", "b").sum ^
So far so good. Let's say I want to have some type of collection, My2Col :
class My2Col[A](a1 : A, a2 : A)
But I want to point out that if done using A : Numeric , and then a2 > a1 . However, it is quite fair to have it done with A , which is not numeric.
My2Col("a", "b") //OK My2Col("b", "a") //OK My2Col(1, 2) //OK My2Col(2, 1) //THROW IllegalArgumentException
Does anyone have any ideas on how I can do this?
PS. If anyone has suggestions for improving the title of the question, I'm all ears
scala typeclass
oxbow_lakes
source share