我在scala中创建了这个案例类和函数:
abstract class Building[T]
case class University[T](a: Building[T], b: Building[T], c: T) extends Building
def u[A,B](a: Building[A]): Building[B] = a match {
case n: University[A] => University[B](n.a, n.b, n.c);
}
然而,它在编译时说明了这一点:
[错误] test.scala:357: 类型不匹配; [错误]发现:test.abc.def.University [B] [error] required:test.abc.def.Building [B]
我做错了什么?
答案 0 :(得分:1)
University
必须延伸Building[T]
,而不仅仅是Building
case class University[T](a: Building[T], b: Building[T], c: T) extends Building[T]
这是完整的代码
abstract class Building[T]
case class University[T](a: Building[T], b: Building[T], c: T) extends Building[T]
在u
函数中,输出类型为Building[B]
。您正在返回University[B]
但University[B]
需要Building[B]
b,即Building[B]
和c
B
。
n.a
返回Building[A]
而不是Building[B]
,因此University[B]
需要两个Building[B]
和一个B
。您无法通过n.a
,n.b
和n.c
来创建university[B]
。
为了使代码编译,我改变了输出类型并返回University[B]
def u[A,B](a: Building[A]): Building[A] = a match {
case n: University[A] => University[A](n.a, n.b, n.c);
}
更正代码
abstract class Building[T]
case class University[T](a: Building[T], b: Building[T], c: T) extends Building[T]
def convert[A, B](a: A): B = ???
def bConvert[A, B](building: Building[A]): Building[B] = ???
def u[A,B](a: Building[A]): Building[B] = a match {
case n: University[A] => University[B](bConvert(n.a), bConvert(n.b), convert(n.c));
}