Use context bound in type alias

后端 未结 2 1286
梦谈多话
梦谈多话 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)
    

提交回复
热议问题