Tuesday, October 20, 2015

Type constraints in Scala

[T <: U] introduces a type variable with an upper bound constraint. T <:< U is a type, and a value of this type is a proof that T is a subtype of U
the latter can be useful if T is introduced with no such constraint, when some operations require the upper bound. (Kudos to @tpolecat)

  def firstLast[A, C](it: C)(implicit ev: C <:< Seq[A]) = {
    (it.head, it.tail)

  firstLast(List(1, 2, 3, 4))
  class Pair[T](val v1: T, val v2: T) {
    def smaller(implicit ev: T <:< Ordered[T])  = {
      if(v1 < v2) v1 else v2