繁体   English   中英

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

[英]Suppressing @unchecked warning for a higher-kinded existential type

在Scala 2.10中,给定class 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}]
                                                ^

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

有点猜测:

$ scala210 -language:_
Welcome to Scala version 2.10.4 (OpenJDK 64-Bit Server VM, Java 1.7.0_65).
Type in expressions to have them evaluated.
Type :help for more information.

scala> class Foo[F[_]]
defined class Foo

scala> (null: Any).isInstanceOf[(Foo[F] forSome { type F[_] }) @unchecked]
res0: Boolean = false

弹出窗口告诉我代码块不是很有用。

哦, s/guessing/experimenting

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

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

在我看来,它也不那么冗长。 如果你的名字的case变量(从小写字母或反引号转义,即不是。 _在上面的例子中前: ),你已经有一个asInstanceOf

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM