11

Is it possible to use context bounds in type aliases in Scala?

e.g

type U = A : B
Timo Westkämper
  • 21,824
  • 5
  • 78
  • 111

2 Answers2

14

Instead of having a context bound directly in the type declaration, you'd have to have a separate value declaration that represents the implicit parameter mentioned by JPP.

Whoever defines the type will also have to provide the evidence for the context bound:

trait Generic {
  type U
  implicit val ordering: Ordering[U]  // evidence for U: Ordering

  def max(u1: U, u2: U) = List(u1, u2).max
}

def concrete[T: Ordering] = new Generic {
  type U = T
  val ordering = implicitly[Ordering[T]]
}

assert(concrete[Int].max(1,3) == 3)
Thipor Kong
  • 597
  • 3
  • 8
14

No, because the context bound is actually a shorthand for an extra implicit parameter.

For instance:

def sort[A : Ordering](xs: Seq[A])

is a shorthand form for

def sort[A](xs: Seq[A])(implicit ordering: Ordering[A])

and this cannot be represented in a type definition.

Jean-Philippe Pellet
  • 59,296
  • 21
  • 173
  • 234