禁止使用更高类型的存在类型的@unchecked警告 [英] Suppressing @unchecked warning for a higher-kinded existential type

查看:124
本文介绍了禁止使用更高类型的存在类型的@unchecked警告的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Scala 2.10中,给定class Foo[F[_]],我不会写

In Scala 2.10, given class Foo[F[_]], I can't write

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批注放置在不同的位置,但是它们都不起作用:

I can write x.isInstanceOf[Foo[F] forSome { type F[_]] }, which gives an unchecked warning. I've tried placing @unchecked annotation in different places, but none of them work:

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}]
                                                ^

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

Is there any way to write this existential type without a warning?

推荐答案

通过模式匹配,您可以避免警告:

With pattern matching you can keep the warnings away:

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

在我看来,它也不那么冗长.如果您命名case变量(以小写字母开头或以反引号转义,即不是_,如上述示例中的:之前),则您已经有一个asInstanceOf.

It is also a bit less verbose in my opinion. In case you name the case variable (starting with lower case letter or escaped with back quotes, ie. not _ as in the above example before :), you already have an asInstanceOf.

这篇关于禁止使用更高类型的存在类型的@unchecked警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆