Scala:为isInstanceOf忽略通用抽象类型 [英] Scala : Generic abstract type ignored for isInstanceOf

查看:146
本文介绍了Scala:为isInstanceOf忽略通用抽象类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人能解释为什么这段代码的输出是 true true ,而不是 true false



我还想知道如何使用 true false 的输出> def apply(in:Any)。我也尝试过参数化类型,并且仍然得到 true true 而不是 true false

  object TestClass extends App {b 
$ b val xTrue = TypeXObject(TypeX(s))
val xFalse = TypeXObject(TypeY(1))
}

案例类TypeX(string:String)

案例类TypeY(int:Int)

对象TypeXObject extends HasAbstractType {覆盖类型T = TypeX}

对象TypeYObject extends HasAbstractType {覆盖类型T = TypeY}

抽象类HasAbstractType {
类型T
def apply(in:Any):Any = {
println(in.isInstanceOf [T])
in
}
}

答案:

issues.scala-lang.org/browse/ SI-5042 - 通过文章和附加文章,我发现可以通过 manifest [T1] .erasure.isInstance(t1)获取 true false 清单[T1] .erasure.isInstance(t2)

解决方案

当我编译你的代码时,我收到以下编译器消息:

  [warn] there是一个未经检查的警告;重新运行并带有-unchecked以获取详细信息
[警告]发现一个警告

code> -unchecked 给编译器,我创建一个build.sbt包含:

  scalacOptions ++ = Seq( -  unchecked,-deprecated)//(我弃用了好的措施)

然后当我编译时,我得到了这个启发性的警告:

pre $ [warn] / home / lwickland / f /f.scala:18:HasAbstractType.this.T类型的抽象类型HasAbstractType.this.T未被选中,因为它被擦除消除
[warn] println(in.isInstanceOf [T])

此时,我必须将您引用到类型擦除的优秀解释以及如何绕过它。

Can someone explain why the output of this code is true true, instead of true false.

I would also like to know how I could achieve a output that is true false using def apply(in:Any). I've tried parameterised types too, and still i get true true instead of true false.

 object TestClass extends App {

  val xTrue = TypeXObject(TypeX("s"))
  val xFalse = TypeXObject(TypeY(1))
 }

 case class TypeX(string:String)

 case class TypeY(int:Int)

 object TypeXObject extends HasAbstractType{override type T = TypeX}

 object TypeYObject extends HasAbstractType{override type T = TypeY}

 abstract class HasAbstractType {
   type T
   def apply(in:Any):Any = {
     println(in.isInstanceOf[T])
     in
   }
 }

Answer:

issues.scala-lang.org/browse/SI-5042 - With article and the attached article i found that I can get the true false with manifest[T1].erasure.isInstance(t1) and manifest[T1].erasure.isInstance(t2).

解决方案

When I compile your code I get the following compiler message:

[warn] there were 1 unchecked warnings; re-run with -unchecked for details
[warn] one warning found

To pass -unchecked to the compiler, I create a build.sbt containing:

scalacOptions ++= Seq("-unchecked", "-deprecated") // (I threw in deprecated for good measure)

Then when I compile, I get this enlightening warning:

[warn] /home/lwickland/f/f.scala:18: abstract type HasAbstractType.this.T in type HasAbstractType.this.T is unchecked since it is eliminated by erasure
[warn]     println(in.isInstanceOf[T])

And at that point, I have to refer you to an excellent explanation of type erasure and how to get around it.

这篇关于Scala:为isInstanceOf忽略通用抽象类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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