Scala在复制时保留case类对象的类型参数

时间:2017-11-03 07:06:49

标签: scala generics

我有以下代码

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}}

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]]