Scala:案例类和模式匹配

时间:2016-10-16 13:06:15

标签: scala generics pattern-matching case-class

我在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]

我做错了什么?

1 个答案:

答案 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.an.bn.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));
}