gpt4 book ai didi

scala - 无形类型转换上的模式匹配好吗?

转载 作者:行者123 更新时间:2023-12-01 13:58:44 25 4
gpt4 key购买 nike

我可以在 google 上找到的所有使用 Typeable 强制转换的示例都涉及 for 表达式。这对我有用,但我想知道这是否可以。我是 shapeless 的新手:这是我在 lib 中的第一个导入。

import shapeless.Typeable._

val blarg: Future[Any] = (worker ? ListOfLongsPlx(foo)) // I know Any === Try[List[Long]]
blarg.map {
_.cast[Try[List[Long]]] match {
case Some(Success(xs)) => xs
case Some(Failure(f)) => /* reporting the failure or just default: */ ; List()
case None => /*reporting bad cast just a default: */ List()
}
}

我应该预料到这种模式会出现问题吗?

需要说明的是,这通过了我的测试。

最佳答案

你的方法很好(虽然我不明白那个特定的代码是如何工作的,因为 Try 不是 Future),但你实际上可以得到一个更好的模式中的语法与 TypeCase 匹配:

import shapeless.TypeCase
import scala.util.{ Failure, Success, Try }

val thing: Any = Try(List(1L, 2L))

val TryListLongCase = TypeCase[Try[List[Long]]]

thing match {
case TryListLongCase(Success(xs)) => xs
case TryListLongCase(Failure(f)) => println(f); Nil
case _ => println("Some unexpected thing"); Nil
}

结果将被适本地输入为 List[Long]

关于scala - 无形类型转换上的模式匹配好吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25654958/

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