Scalac发现错误:scala.Boolean(false)required:java.lang.Bool
发布时间:2020-12-16 19:14:11 所属栏目:安全 来源:网络整理
导读:下面的代码检查基本身份验证.这里resp是401未经授权的响应.我检查是否存在Authorization标头,如果存在,我验证其值,否则我调用resp: def validate(authHeader: String): Boolean = { //........} val authHeader = Option(request.getHeader("Authorization"
下面的代码检查基本身份验证.这里resp是401未经授权的响应.我检查是否存在Authorization标头,如果存在,我验证其值,否则我调用resp:
def validate(authHeader: String): Boolean = { //........ } val authHeader = Option(request.getHeader("Authorization")) authHeader match { case Some(header) if header.startsWith("Basic ") => validate(header) match { case false => resp } case _ => resp } 当我编译它时,它给行匹配错误{case false => resp}发现:scala.Boolean(false)required:java.lang.Boolean.我很困惑为什么它处理scala布尔不同于java布尔值. 我注意到文件开头有一行import java.lang._(我不知道为什么).我评论了它,代码发出警告而不是错误: warning: match may not be exhaustive. It would fail on the following input: true 我想这是因为我没有写这个案例.但是什么原因导致原始错误发生,为什么它只发生在import java.lang._? 编辑: 以下是该问题的最小示例: val f: java.lang.Boolean = false val f2: scala.Boolean = false /* The following line produces this error: error: type mismatch; found : scala.Boolean(false) required: java.lang.Boolean */ f match { case false => 5 } /* The following line produces this warning: warning: match may not be exhaustive. It would fail on the following input: true */ f2 match { case false => 5 } 解决方法
似乎隐式转换在模式匹配的情况下不起作用.
考虑: scala> case class Foo(x: Int) defined class Foo scala> case class Bar(x: Int) defined class Bar scala> implicit def foo2bar(x: Foo) = Bar(x.x) foo2bar: (x: Foo)Bar scala> Foo(3) match { case Foo(3) => 3; case _ => 4 } res19: Int = 3 scala> Foo(3) match { case Bar(3) => 3; case _ => 4 } <console>:14: error: constructor cannot be instantiated to expected type; found : Bar required: Foo Foo(3) match { case Bar(3) => 3; case _ => 4 } ^ 与之比较: scala> val f: java.lang.Boolean = false f: Boolean = false scala> f.<TAB> asInstanceOf booleanValue compareTo isInstanceOf toString scala> f || true res21: Boolean = true 隐式转换在这里工作,但不在这里: scala> f match { case false => 3; case true => 4 } <console>:15: error: type mismatch; found : scala.Boolean(false) required: java.lang.Boolean f match { case false => 3; case true => 4 } ^ <console>:15: error: type mismatch; found : scala.Boolean(true) required: java.lang.Boolean f match { case false => 3; case true => 4 } ^ 我同意这是非常违反直觉但我怀疑它可以修复而不在语言中引入特殊的外壳,或者让scalac以某种方式识别所有模式属于单一类型的模式匹配,并尝试找到对该类型的隐式转换.解决方法是进行显式的asInstanceOf [Boolean]强制转换.虽然奇怪的是以下工作正常: scala> "foobar".startsWith("foo") match { case true => 3 ; case false => 4 } res26: Int = 3 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
推荐文章
站长推荐
热点阅读