scalagenericstypeshigher-kinded-typescontext-bound

How to define a context bound with a higher kinded Type (Type Constructor)


I have tried the following

def test[Option[T]: Ordering](value1: Option[T], value2: Option[T]) = {
  val e = implicitly(Ordering[Option[T]].compare(value1, value2))
}

but does not work ? Any idea what's the issue ?

EDIT

This of course works

def test[T](value1: Option[T], value2: Option[T]) (implicit ev: Ordering[Option[T]]) = {
  ev.compare(value1, value2)
}

Solution

  • If you really insist on using a context bound you can write a type lambda:

    def test[T: ({type L[x] = Ordering[Option[x]]})#L](value1: Option[T], value2: Option[T]) = {
      val e = implicitly(Ordering[Option[T]].compare(value1, value2))
    }
    

    Or with the kind-projector plugin you should be able to make this a bit cleaner:

    def test[T: Lambda[x => Ordering[Option[x]]]](value1: Option[T], value2: Option[T]) = {
      val e = implicitly(Ordering[Option[T]].compare(value1, value2))
    }