In scala, we can use implicit typeclasses to conditionally add methods onto a parameterized type dependent on that type's parameters. For example, Iterator.sum
:
def sum[B >: A](implicit num: Numeric[B]): B = foldLeft(num.zero)(num.plus)
There must be an instance of the Numeric
typeclass for this method to even be called:
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 collection type, My2Col
:
class My2Col[A](a1 : A, a2 : A)
But I want to mandate that, if this is made with a A : Numeric
, then a2 > a1
. However, it is entirely valid for it to be made with an A
which is not numeric.
My2Col("a", "b") //OK
My2Col("b", "a") //OK
My2Col(1, 2) //OK
My2Col(2, 1) //THROW IllegalArgumentException
Has anyone any ideas as to how I might do this?
PS. If anyone has any suggestions for a better question title, I'm all ears
class My2Col[A](a1 : A, a2 : A)(implicit num: Numeric[A] = null){
for{check <- Option(num); if(check.gteq(a1, a2))}
throw new IllegalArgumentException
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With