gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 04:54:16 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com