加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

scala – 为更高级别的存在类型抑制@unchecked警告

发布时间:2020-12-16 18:36:05 所属栏目:安全 来源:网络整理
导读:在 Scala 2.10中,给定类Foo [F [_]],我不能写 scala x.isInstanceOf[Foo[_]]console:10: error: _$1 takes no type parameters,expected: one x.isInstanceOf[Foo[_]] ^ 要么 scala x.isInstanceOf[Foo[_[_]]]console:11: error: _$1 does not take type par
在 Scala 2.10中,给定类Foo [F [_]],我不能写

scala> x.isInstanceOf[Foo[_]]
<console>:10: error: _$1 takes no type parameters,expected: one
              x.isInstanceOf[Foo[_]]
                                 ^

要么

scala> x.isInstanceOf[Foo[_[_]]]
<console>:11: error: _$1 does not take type parameters
              x.isInstanceOf[Foo[_[_]]]
                                 ^

我可以写一个x.isInstanceOf [Foo [F] forSome {type F [_]]},它会给出一个未经检查的警告.我尝试在不同的地方放置@unchecked注释,但它们都不起作用:

scala> x.isInstanceOf[Foo[H] @unchecked forSome {type H[_]}]
<console>:11: warning: abstract type H in type Foo[H] @unchecked forSome { type H[_] <: Any } is unchecked since it is eliminated by erasure
              x.isInstanceOf[Foo[H] @unchecked forSome {type H[_]}]
                            ^

scala> x.isInstanceOf[Foo[H @unchecked] forSome {type H[_]}]
<console>:11: warning: abstract type H in type Foo[H @unchecked] is unchecked since it is eliminated by erasure
              x.isInstanceOf[Foo[H @unchecked] forSome {type H[_]}]
                            ^
<console>:11: error: kinds of the type arguments (? @unchecked) do not conform to the expected kinds of the type parameters (type F) in class Foo.
? @unchecked's type parameters do not match type F's expected parameters:
<none> has no type parameters,but type F has one
              x.isInstanceOf[Foo[H @unchecked] forSome {type H[_]}]
                                               ^

scala> x.isInstanceOf[Foo[H] forSome {type H[_] @unchecked}]
<console>:1: error: `=',`>:',or `<:' expected
       x.isInstanceOf[Foo[H] forSome {type H[_] @unchecked}]
                                                ^

有没有办法在没有警告的情况下编写这种存在类型?

解决方法

通过模式匹配,您可以保留警告:

x match {case _: Foo[_] => ???}

在我看来,它也不那么冗长.如果你命名case变量(以小写字母开头或用后引号转义,即不是_之前的例子:),你已经有了asInstanceOf.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读