scala – 在类类型参数中使用上下文绑定
发布时间:2020-12-16 18:41:07 所属栏目:安全 来源:网络整理
导读:我的印象是上下文边界只适用于方法: trait Target[T]class Post { def pinTo[T : Target](t:T)} 显然,上下文边界也可以用于inclass(并且可能是trait): trait Target[T]class Post[T:Target] { def pintTo[T](t:T) } 现在我对如何向Post提供证据感到困惑?
我的印象是上下文边界只适用于方法:
trait Target[T] class Post { def pinTo[T : Target](t:T) } 显然,上下文边界也可以用于inclass(并且可能是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有关 解决方法
上下文边界的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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |