Using a context bound in a class type parameter

后端 未结 1 1009
滥情空心
滥情空心 2021-01-18 19:41

I was under the impression that context bounds would work only on methods:

trait Target[T]

class Post {
  def pinTo[T : Target](t:T)
}

app

相关标签:
1条回答
  • 2021-01-18 20:27

    The A: Foo notation for context bounds is only a shortcut for asking for an implicit value parameter of type Foo[A]. Since traits do not have constructor value parameters, you can not use this with a trait:

    trait Foo[A]
    
    trait Bar[A: Foo] // "error: traits cannot have type parameters with context bounds..."
    

    Whereas in classes it's possible:

    class Bar[A: Foo] {
      def foo: Foo[A] = implicitly[Foo[A]]
    }
    

    Which is just a different way of writing

    class Bar[A](implicit foo: Foo[A])
    

    You provide the evidence like you do in any other normal method call:

    new Bar[Int]()(new Foo[Int] {})  // explicitly
    

    Or:

    implicit val iFoo = new Foo[Int] {}
    
    new Bar[Int]  // implicitly
    
    0 讨论(0)
提交回复
热议问题