Scala:case 类 和模式匹配
Scala: case classes and pattern matching
我已经创建了这个案例 类 并在 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);
}
但是编译的时候是这样说的:
[error]
test.scala:357:
type mismatch; [error] found : test.abc.def.University[B]
[error] required: test.abc.def.Building[B]
我做错了什么?
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]
需要 a 是 Building[B]
b 又是 Building[B]
和 c
是 B
.
n.a
returns 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));
}
我已经创建了这个案例 类 并在 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);
}
但是编译的时候是这样说的:
[error] test.scala:357: type mismatch; [error] found : test.abc.def.University[B] [error] required: test.abc.def.Building[B]
我做错了什么?
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]
需要 a 是 Building[B]
b 又是 Building[B]
和 c
是 B
.
n.a
returns 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));
}