scala - 如何避免 'Non-variable type argument is unchecked since it is eliminated by erasure' ?

标签 scala compiler-warnings future

我正在处理的一个项目有以下代码:

val ftr1: Future[Try[(Date, String)]] = Future {
  if (someCondition) {
    // some code
    val amazonClient = Try[new com.amazonaws.services.s3.AmazonS3Client(...)]
    amazonClient.map { c => 
    // doing some stuff
    (new Date, "SomeString")
    }
  } else {
    // some code
    Failure(new Exception)
  }
}

Future.firstCompletedOf(Seq(ftr1, anotherFuture)) map {
  case t: Try[(Date, String)] => {
    t match {
      case Success(r) => //do some things
      case _ => //do some another things
  }
  case _ => //do some another things
}

因此,在编译期间,我有以下警告:

[warn] non-variable type argument java.util.Date in type pattern java.util.Date, String) is unchecked since it is eliminated by erasure





[warn] case t: (Date, String) => //do some things



我实际上不明白,这些警告是什么意思,如何重构这段代码以摆脱这些警告?

最佳答案

Try[+T]是一个抽象类,您不能为其创建实例。

有两个案例类继承自它,SuccessFailure ,您应该真正使用它。

编译器警告您,在编译时,类型删除将删除这些类型,因此对它们进行匹配不会得到您想要的结果。有关更多信息,请访问 How do I get around type erasure on Scala? Or, why can't I get the type parameter of my collections?

但是,如果您只需匹配 Success 就可以完全避免这一切。和 Failure减少比赛中不必要的嵌套:

val ftr1: Future[Try[(Date, String)]] = Future {
  if (someCondition) {
    // some code
    val amazonClient = Try { /* stuff */ }
    amazonClient.map { c => 
    // doing some stuff
    (new Date, "SomeString")
  } else Failure(new Exception)
}

Future.firstCompletedOf(Seq(ftr1, anotherFuture)) map {
   case Success((date, myString)) => /* do stuff */
   case Failure(e) => log(e)
}

关于scala - 如何避免 'Non-variable type argument is unchecked since it is eliminated by erasure' ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38618071/

相关文章:

scala - 单例对象可以扩展特征吗?

scala - liftweb - 更改基本 url

java - 为什么在这种情况下使用 scala 并行性会降低性能?

C++ 编译器在使用 boost::xpressive 时给出警告页面

c++ - Vim Syntastic 显示警告并设置警告级别

c++ - 如何手动创建将在析构函数中阻塞的 future

scala - 排序 `Future` s 超时

scala - 如何获取第一个成功完成的Future?

Scala:如何在子线程中捕获异常

c# - 发生基类虚方法隐藏时如何强制编译报错?