Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a validity check dependent on a typeclass (Optional implicits)

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

like image 978
oxbow_lakes Avatar asked Dec 06 '10 08:12

oxbow_lakes


1 Answers

class My2Col[A](a1 : A, a2 : A)(implicit num: Numeric[A] = null){
  for{check <- Option(num); if(check.gteq(a1, a2))}
     throw new IllegalArgumentException
}
like image 70
Vasil Remeniuk Avatar answered Oct 05 '22 18:10

Vasil Remeniuk