简体   繁体   English

在Scala中通过擦除消除了返回类型

[英]Return type eliminated by erasure in Scala

Consider the following Scala code snippet: 考虑以下Scala代码片段:

def func(param: Any): Int = param match {
  case f: (String => Int) => f("apple")
  case i: Int => i
}

println(func((s: String) => s.length))

Works as expected, however, at compilation I get the following warning: 按预期工作,但是,在编译时我收到以下警告:

<console>:11: warning: non-variable type argument String in type pattern String => Int is unchecked since it is eliminated by erasure
         case f: (String => Int) => f("apple")

How can I get rid of this warning message? 如何摆脱此警告消息?

Thanks your help in advance! 预先感谢您的帮助!

The reason why you get the message is because of Java's generic type erasure . 之所以收到该消息,是因为Java的泛型类型Erase In this particular case, your function which is of type Function[String, Int] will be matched by any Function[A, B] . 在这种特殊情况下,类型为Function[String, Int] Function[A, B]将与任何Function[A, B]匹配。

In order to get rid of this warning you should use scala typetags which will allow you to differentiate between the different function types. 为了摆脱此警告,您应该使用scala类型标签 ,这将使您能够区分不同的函数类型。

The code snippet is below, 下面的代码段

import scala.reflect.runtime.universe._

object Answer {
 def function[A](param: A)(implicit tt: TypeTag[A]): String = param match {
   case f: (String => Int) @unchecked if typeOf[String => Int] =:= typeOf[A] => f("apple").toString
    case f: (Int => String) @unchecked if typeOf[Int => String] =:= typeOf[A] => f(32 + 1)
    case s: String => s"hello $s"
  }

  def main (args: Array[String]) {
     println(function((s: String) => s.length))
     println(function((i: Int) => i.toString))
     println(function("world"))
  }
}

The key part is to have an implicit TypeTag[A] which is added at compile time which includes the metadata that the function typeOf needs to check the types of A against anything else. 关键部分是在编译时添加一个implicit TypeTag[A] ,其中包含元数据,函数typeOf需要对照该元数据检查A的类型。

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

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