scala - 用“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
错误非常明显,问题确实在于A
s 也将被强制转换为B
s 并且这将失败。
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 3中尝试用括号括(s: B)
起来
for {
(s: B) <- listOfSomething
} yield s
然后似乎脱糖
listOfSomething
.withFilter { case (s: B) => true; case _ => false }
.map({ case (s: B) => s })
推荐阅读
- mysql - [Laravel 8.x][Eloquent] 将行复制到 mysql 中的另一个表
- python - Python, Bcrypt 使用 SQL 连接器检查密码
- python - Pandas 将函数应用于采用前一列值的列
- python - 如何在 PySpark 数据帧上的列(具有数据类型数组(字符串))上应用过滤器?
- python - 如何在数据框范围内的列中添加 1
- gitlab - 在 Gitlab CI 上设置 PostGIS 失败:psql 无法连接到服务器:没有这样的文件或目录
- bash - 如何在 bash 脚本中评估管道的结果
- go - 如何在不改变原始切片的情况下对切片进行排序
- python - python生成器到熊猫数据框
- json - 如何在处理异常的函数中返回 Func(Of T, IEnumerable(Of T))?