我有以下代码
class GM
class BM extends GM
case class GenException(message: String) extends RuntimeException(message) {
override def toString: String = s"${this.toString()}"
}
case class Hello[T <: GM](t: Try[T])
object Main extends App {
val first: Hello[BM] = Hello.apply(Success.apply(new BM))
val second: Hello[Nothing] = first.copy(t = Failure(GenException("hello")))
}
正如您所看到的,scala将秒的类型推断为Hello[Nothing]
,但我希望它保留对象对其的类型,即它在类型{上的计算失败} {1}}
答案 0 :(得分:2)
写
val second: Hello[BM] = first.copy(t = Failure(GenException("hello")))
Scala推断类型为Hello[Nothing]
,因为您明确地写了Hello[Nothing]
。
import scala.reflect.runtime.universe.TypeTag
def getTypeTag[T](v: T)(implicit typeTag: TypeTag[T]): TypeTag[T] = typeTag
val second = first.copy(t = Failure(GenException("hello")))
println(getTypeTag(second)) //TypeTag[Hello[Nothing]]
val second: Hello[Nothing] = first.copy(t = Failure(GenException("hello")))
println(getTypeTag(second))//TypeTag[Hello[Nothing]]
val second: Hello[BM] = first.copy(t = Failure(GenException("hello")))
println(getTypeTag(second))//TypeTag[Hello[BM]]