更新时间:2023-11-10 21:06:10
最干净的解决方案是,IMO,您找到的与类型捕获模式匹配的解决方案.您可以通过将模式直接集成到您的理解中来使其简洁,并希望具有可读性,如下所示:
The cleanest solution is, IMO, the one you found with the type-capture pattern match. You can make it concise, and hopefully readable, by integrating the pattern directly inside your for comprehension, as follows:
for ((a, b: C[t]) <- list) {
b.f(a.asInstanceOf[t])
}
小提琴:http://www.scala-js-fiddle.com/gist/b9030033133ee94e8c10a7777
Fiddle: http://www.scala-js-fiddle.com/gist/b9030033133ee94e8c18ad772f3461a0
如果你还没有理解,不幸的是,相应的模式分配不起作用:
If you are not in a for comprehension already, unfortunately the corresponding pattern assignment does not work:
val (c, d: C[t]) = (a, b)
d.f(c.asInstanceOf[t])
那是因为 t
不在第二行的范围内.在这种情况下,您将不得不使用完整模式匹配.
That's because t
is not in scope anymore on the second line. In that case, you would have to use the full pattern matching.