在Scala中,如何限制多个参数必须是同一类型内的类型?
发布时间:2020-12-16 18:06:34 所属栏目:安全 来源:网络整理
导读:我正在尝试使用泛型的路径依赖类型. 我有两个类,C2类嵌套在C1中. case class C1(v1: Int) { case class C2(v2: Int)} 我在这里有两个C1类对象: object O1 extends C1(1)object O2 extends C1(2) 我想编写一个接受C2类型的多个参数的方法.并且所有这些参数必
我正在尝试使用泛型的路径依赖类型.
我有两个类,C2类嵌套在C1中. case class C1(v1: Int) { case class C2(v2: Int) } 我在这里有两个C1类对象: object O1 extends C1(1) object O2 extends C1(2) 我想编写一个接受C2类型的多个参数的方法.并且所有这些参数必须属于C1的同一对象. 例如: foo(O1.C2(10),O1.C2(11)) // all the C2 is inside the same O1 foo(O1.C2(10),O2.C2(20)) // not good,will not compile 我已经尝试过一些方法来编写这种方法,但没有人工作. 第一个: def print1(p1: C1#C2,p2: C1#C2): Unit = { println(p1.v2,p2.v2) } print1(O1.C2(1111),O2.C2(2222)) // Not requited that p1 & p2 should have the same object of C1 第二个: def print2(p1: O1.C2,p2: O1.C2): Unit = { println(p1.v2,p2.v2) } print2(O1.C2(1111),O1.C2(1111)) // Can only accept the C2 inside O1 第三个: def print3[T <: C1#C2](p1: T,p2: T): Unit = { println(p1.v2,p2.v2) } print3(O1.C2(1111),O2.C2(2222)) // The same as the first one. 最后一个: // def print2[U <: C1](p1: U.C2,p2: U.C2): Unit = { // println(p1.v2,p2.v2) // } // Not compile,Error: not found: value U 无论如何,我可以存档吗? 解决方法
你可以这样做,但你也需要传递对象本身:
def print(o: C1)(p1: o.C2,p2: o.C2) = ... print(O1)(O1.C2(1111),O2.C2(2222)) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |