【发布时间】:2017-05-10 20:58:38
【问题描述】:
以下代码不起作用:
trait A {
type C
val Extract: {
def unapply(c: C): Option[Int]
}
}
错误如下:
错误:结构细化中的参数类型可能不引用在该细化之外定义的抽象类型
我想写上面的内容,以便强制特征 A 的用户定义具有 unapply 方法的对象或值,以便我可以在模式匹配中使用它。
感谢"Parameter type in structural refinement may not refer to an abstract type defined outside that refinement" 和Scala: "Parameter type in structural refinement may not refer to an abstract type defined outside that refinement"(见下文),我找到了两种解决方法,但第一种方法强制继承特征,如果我尝试链接到外部库,这是不可行的;其次,我放弃了覆盖 Extract 以将更多方法放入其中的可能性。
解决方法
trait A {
type C
trait Extractable {
def unapply(c: C): Option[Int]
}
val Extract: Extractable
}
trait A {
type C
def extract(c: C): Option[Int]
object Extract {
def unapply(c: C): Option[Int] = extract(c)
}
}
是否有任何方式(可能除了结构类型)可以表达用户可以按照他想要的方式实现Extract 的想法,只要它具有请求签名的方法unapply?
【问题讨论】:
标签: scala