【问题标题】:Using a context bound in a class type parameter使用绑定在类类型参数中的上下文
【发布时间】:2013-12-07 10:32:11
【问题描述】:

我的印象是上下文边界只适用于方法:

trait Target[T]

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

显然上下文边界也可以用于class(可能还有trait):

trait Target[T]

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

现在我很困惑如何将证据提供给Post

class Business
implicit object ev extends Target[Business] // is implicit necessary here ?

val p = new Post[Business] // ?? how do I provide ev ? 

Modeling a binary relationship between two types相关

【问题讨论】:

    标签: scala typeclass implicit parametric-polymorphism


    【解决方案1】:

    上下文边界的A: Foo 表示法只是请求Foo[A] 类型的隐式值参数的快捷方式。由于特征没有构造函数值参数,您不能将其与特征一起使用:

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

    而在课堂上是可能的:

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

    这只是一种不同的写作方式

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

    您像在任何其他常规方法调用中一样提供证据:

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

    或者:

    implicit val iFoo = new Foo[Int] {}
    
    new Bar[Int]  // implicitly
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-05
      • 2012-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-03
      相关资源
      最近更新 更多