trait targetingRelation[targetingType[_],TargetedType] class Business class Person class Post[Target | targetingRelation[Business,Post] ] { def target:Target } class Like[Target | targetingRelation[Business,Like] ] { def target:Target }
在这里,我发明了一个T | P [T]符号表示类型参数T,使得它满足某些属性P [T](或T:|:P [T],如果它携带更多的类型吸引力).代码中的其他地方我想要声明如下:
object canPostAboutBusiness extends targetingRelation[Post,Business] object canLikeBusiness extends targetingRelation[Like,Business]
这些对象实际上是证据,类似于Haskell类型类.所以这会打字检查:
val p = new Post[Business] val l = new Like[Business]
但不是这个:
val p = new Post[Person] val l = new Like[Person]
就我对Scala的认识而言,我无法以令人满意的方式对这种特殊情况进行建模.现在我坚持认为这不是子类型,因为商业不是:
class Business extends targetingRelation[Post,Business] with targetingRelation[Like,Business]
事实上,商业仍然完全不了解邮政是非常可取的.这种关系实际上不属于邮政和商业.此外,我认为上面的代码甚至不会编译开始,因为Business继承了两次targetingRelation.很受欢迎.
解决方法
import scala.language.higherKinds trait targetingRelation[A[_],B] class Business class Person // Using explicitly declared implicit parameter: class Post[T](implicit ev: targetingRelation[Post,T]) // Using a "context bound". The Syntax is a little hairy and uses // a type lambda because targetingRelation takes multiple type params class Like[T : ({type S[x] = targetingRelation[Like,x]})#S] implicit object canPostAboutBusiness extends targetingRelation[Post,Business] implicit object canLikeBusiness extends targetingRelation[Like,Business]
然后,您可以使用Business实例化类
scala> val p = new Post[Business] p: Post[Business] = Post@374c991a scala> val l = new Like[Business] l: Like[Business] = Like@1fd348f8
但不是与人
scala> val p1 = new Post[Person] <console>:15: error: Could not find implicit value for parameter ev: targetingRelation[Post,Person] val p1 = new Post[Person] ^ scala> val p2 = new Like[Person] <console>:15: error: Could not find implicit value for evidence parameter of type targetingRelation[Post,Person] val p2 = new Like[Person] ^
如果你从“scala类型类”中搜索,你会发现大量的explanations of the details如何工作,但基本上,你需要构造函数采用targetingRelation [targetingType [_],TargetedType]类型的隐式参数,然后放置一个隐含的在构造类(Post或Like)时范围内的那种类型.隐式用作“证据”,即TargetedType具有类型类的实例(并且扮演在其他语言类型类实现中自动传递的显式方法字典的角色).
事实上,scala有一些同步糖可以帮助解决这个问题,称为Context Bound.这导致方法写成:
def a[A: B] = ???
被翻译成
def a[A](implicit ev: B[A]) = ???
在您的特定示例中,上下文边界语法有点棘手,因为有多个类型参数,但可以按照this SO question描述的那样完成.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。