首页 > 解决方案 > 用“case-like”类型检查来理解

问题描述

以下代码未编译。listOfSomething尝试对(例如case s:String => //dosomething)中的项目执行“类似案例”的类型检查

class A

class B extends A

class C extends A

val listOfSomething: List[A] = List.empty[A]
val result = for {
  s:B <- listOfSomething
} yield s

错误非常明显,问题确实在于As 也将被强制转换为Bs 并且这将失败。

Error:(41, 15) type mismatch;
found   : B => B
required: A => ?
s: B <- listOfSomething

我的问题如下:我在这里唯一的选择是做以下事情吗?

val result = for {
  s <- listOfSomething if s.isInstanceOf[B]
} yield s

或者您是否看到任何其他选项,例如更优雅的“case-like”类型检查?

编辑:我不想使用,因为我想在其中包含多个条目以进行理解,如果我要使用s 例如collect,我将不得不创建一个深度嵌套的结构collect

val result = for {
  s:B <- listOfSomething
  other <- anotherList if s.foo == "foo" && s.bar == "bar"
  another <- yetAnotherList if other.x == "x" && other.y == "y"
  .... // goes on
} yield s

标签: scala

解决方案


Scala 3中尝试用括号括(s: B)起来

for {
  (s: B) <- listOfSomething
} yield s

然后似乎脱糖

listOfSomething
  .withFilter { case (s: B) => true; case _ => false }
  .map({ case (s: B) => s })

推荐阅读