繁体   English   中英

使用类类型参数中的上下文绑定

[英]Using a context bound in a class type parameter

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

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 ? 

建模两种类型之间的二元关系有关

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM