首页 文章

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

提问于
浏览
3

我正在处理的项目有以下部分代码:

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]类型为模式java.util.Date,String中的非变量类型参数java.util.Date未被选中,因为它被擦除消除了

[warn] case t:(Date,String)=> //做一些事情

我实际上不明白,这些警告意味着什么,为了摆脱这些警告,如何重构这些代码呢?

1 回答

  • 1

    Try[+T] 是一个抽象类,您无法创建它的实例 .

    有两个继承自它的case类, 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)
    }
    

相关问题