![](/img/trans.png)
[英]In scala, how to instruct the compiler to realise the equivalence of two abstract types?
[英]Is it possible for the Scala compiler to understand overridden Abstract Types
语境:
我试图在 RESTful 端点中使用由 Jackson, JsonSubTypes 提供的多态子类型。 各种请求主体之间有一些共性,所以我有:
abstract class A extends Translatable {
val infoA: String
val infoB: String
}
case class B(
infoA: String,
infoB: String,
infoC: String,
infoD: Int
) extends A {
override type T = B
def translate(
requestInfo: String,
request: B
): String = s"<$infoA,$infoB>:$infoC-${infoD.toString}"
}
case class C(
infoA: String,
infoB: String,
infoC: Array[String]
) extends A {
override type T = C
def translate(
requestInfo: String,
request: C
): String = s"<$infoA,$infoB>:${infoC.mkString}"
}
具有以下特征,因此不必将传入的A
请求与B
或C
进行模式匹配:
trait Translatable {
type T <: A
def translate(
requestInfo: String,
request: T
): String
}
问题是当我编译它抱怨类型不匹配时:
found: request.type (with underlying type com.program.A)
required: request.T
我尝试了几件事,但无济于事,只有这似乎很接近:
e.g.,
def translate[X](
requestInfo: String,
request: X
)(implicit ev: X <:< A) = ...
(modifying the case class impl. of ^ accordingly)
但这导致
无法证明 com.program.A <:< request.T
关于如何做到这一点的任何想法? 还是我必须忍受模式匹配? 我说是因为第一个代码块仅当我模式匹配并调用具体实现时才起作用。 对于B
或C
的translate
,但我更喜欢只有A
类型参数并在其上调用translate
。 那可能吗?
编辑:添加上面产生编译错误的实例:
class Program {
def doWork(
info: String,
request: A
): String = {
request.translate(
info,
request // compilation fails/complains about this param in both cases
)
}
}
EDIT2:添加限定:我需要在子类型B
& C
覆盖类型,以便在翻译功能中。 我可以调用特定于B
或C
字段
尝试添加具有细化上限的类型参数
def doWork[T0 <: A { type T = T0 }](
info: String,
request: T0
): String = {
request.translate(
info,
request
)
}
doWork("info1", B("infoA1", "infoB1", "infoC1", 1))//<infoA1,infoB1>:infoC1-1
doWork("info2", C("infoA2", "infoB2", Array("infoC21", "infoC22")))//<infoA2,infoB2>:infoC21infoC22
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.