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

How to avoid 'Non-variable type argument is unchecked since it is eliminated by erasure'?

我正在做的一个项目有以下片段代码:

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] 是一个抽象 class,您无法创建其实例。

有两种情况 class 继承自它,SuccessFailure,您应该真正使用它们。

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

但是,如果您简单地匹配 SuccessFailure 以减少匹配中不必要的嵌套,就可以完全避免这一切:

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)
}