当我使用 scala
运行以下代码片段时
import scala.language.reflectiveCalls
def foo(a: Option[Any]): Option[Any] = {
a.filter {
case x: { def bar: Boolean } => x.bar
}
}
object Bar {
def bar: Boolean = true
}
println(foo(Some(Bar)))
我收到警告
warning: a pattern match on a refinement type is unchecked
我试过以下方法:
@unchecked case x: { def bar: Boolean } => x.bar
case (@unchecked x): { def bar: Boolean } => x.bar
case (x @unchecked): { def bar: Boolean } => x.bar
case x: @unchecked { def bar: Boolean } => x.bar
case x: { def bar: Boolean } @unchecked => x.bar
case (x: { def bar: Boolean } @unchecked) => x.bar
case x: ({ def bar: Boolean } @unchecked) => x.bar
case x: { def bar: Boolean } => (x @unchecked).bar
case x: { def bar: Boolean } => (x: { def bar: Boolean } @unchecked).bar
这些都不起作用。这也行不通:
a.filter { any => (any: @unchecked) match {
case x: { def bar: Boolean } => x.bar
}}
如何抑制此警告?
有些相关的链接
This answer似乎在 Some(...)
中成功使用了 @unchecked
,但我不知道如何将它与 filter
一起使用。
最佳答案
{ def ... }
需要一对额外的圆括号:
case x: ({ def bar: Boolean }) @unchecked => x.bar
有了额外的括号,它编译得很好,没有任何警告。
这似乎类似于“经典类型 lambda”的语法,其中
({ type Lam[X] = Foo[X] })#Lam
有效,而
{ type Lam[X] = Foo[X] }#Lam
没有。
关于scala - 将 `@unchecked` 放在哪里以抑制 "pattern match on a refinement type is unchecked"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51615182/