Use context bound in type alias

后端 未结 2 1272
梦谈多话
梦谈多话 2021-01-04 14:15

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

e.g

type U = A : B
相关标签:
2条回答
  • 2021-01-04 14:59

    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)
    
    0 讨论(0)
  • 2021-01-04 15:16

    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.

    0 讨论(0)
提交回复
热议问题