了解具有单一继承的Scala中的TypeTag

时间:2018-01-19 09:16:44

标签: scala

我遇到了下面这段代码,它有一个像这样的特征,并且在其中定义了一些方法:

    trait TypeTaggedTrait[Self] { self: Self =>

  /**
    * The representation of this class's type at a value level.
    *
    * Useful for regaining generic type information in runtime when it has been lost (e.g. in actor communication).
    */
  val selfTypeTag: TypeTag[Self]

  /**
    * Compare the given type to the type of this class
    *
    * Useful for regaining generic type information in runtime when it has been lost (e.g. in actor communication).
    *
    * @return true if the types match and false otherwise
    */
  def hasType[Other: TypeTag]: Boolean =
    typeOf[Other] =:= selfTypeTag.tpe

  /**
    * Attempt to cast this value to the given type.
    *
    * If the types match, the casted version is returned. Otherwise, empty value is returned.
    *
    * Useful for regaining generic type information in runtime when it has been lost (e.g. in actor communication).
    *
    * @return casted version wrapped in `Some` if the cast succeeds, and otherwise `None`
    */
  def cast[Other: TypeTag]: Option[Other] =
    if (hasType[Other])
      Some(this.asInstanceOf[Other])
    else
      None
}

abstract class TypeTagged[Self: TypeTag] extends TypeTaggedTrait[Self] { self: Self =>
  val selfTypeTag: TypeTag[Self] = typeTag[Self]
}

然后我试图像这样实现这个特性:

  case class MyCase(str: String, i: Int)

  final class MyTypeTagged[MyCase] extends TypeTagged[MyCase] {
    ....
    ....
  }

显然,如屏幕截图所示,它无法使用以下消息进行编译。

enter image description here

任何人都可以帮我解决发生的事情吗?如果我给出整个MyTypeTagged [MyCase],它就可以了。我该怎么解释这个?它也期待封闭式。我该怎么解释这个?

0 个答案:

没有答案