在 Scala 3 中,给定这样一个类型别名:
type Test[A] = A | Option[A]
val first: Test[String] = "gandalf"
val second: Test[String] = None
val third: Test[String] = Some("sam")
我如何区分我有两种情况中的哪一种(A
或Option[A]
)?
在尝试编写代码时,我认为主要问题在于编译器和类型,包括Either[String, B], matches
A`。我什至不知道我的问题是否有惯用的解决方案。
这是我最好的尝试,任何一个都失败了:
def get[A](input: Test[A]): A =
input match
case Some(value) => value.asInstanceOf[A]
case None => throw new RuntimeException("Error!")
case _ => input.asInstanceOf[A]
get(first) // "gandalf"
get(second) // Exception!!!
get(third) // sam"
如您所见value
,不识别为与类型参数相同的类型,A
并且A
在运行时无法真正检查底部的情况(尝试case a: A =>
给出编译错误),因此我通过排除其他两个来捕获它。这看起来不是最佳解决方案。