简体   繁体   English

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

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

I was under the impression that context bounds would work only on methods: 我的印象是上下文边界只适用于方法:

trait Target[T]

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

apparently context bounds can be used in class (and presumably trait ) too: 显然,上下文界限也可以在class上使用(也可能是trait ):

trait Target[T]

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

Now I'm confused as to how the evidence can be provided to Post ? 现在我对如何向Post提供证据感到困惑?

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

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

related to Modeling a binary relationship between two types 建模两种类型之间的二元关系有关

The A: Foo notation for context bounds is only a shortcut for asking for an implicit value parameter of type Foo[A] . 上下文边界的A: Foo表示法只是要求Foo[A]类型的隐式值参数的快捷方式。 Since traits do not have constructor value parameters, you can not use this with a trait: 由于traits没有构造函数值参数, 因此不能将其与特征一起使用:

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

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

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