scala - 在子类中生成字符串实现

标签 scala

我有以下特征和实现:

sealed trait NodeIdIdentifier {
    def asString: String
  }
  case class NumericTwoByteIdentifier(value: Byte) extends NodeIdIdentifier {
    override def asString: String = value.toString
  }
  case class NumericFourByteIdentifier(value: Short) extends NodeIdIdentifier {
    override def asString: String = value.toString
  }
  case class NumericIdentifier(value: Int) extends NodeIdIdentifier {
    override def asString: String = value.toString
  }
  case class StringIdentifier(value: String) extends NodeIdIdentifier {
    override def asString: String = value.toString
  }

可以看出,我必须在所有子类中编写 asString 重写。有没有一种优雅的方法来做到这一点?我不喜欢重复覆盖的想法。我宁愿让我的特质定义 asString 行为并将其应用到子类。有任何想法吗?根据上下文绑定(bind)重写它会帮助我编写更优雅的代码吗?我设法通过在我的特征上使用 Any 类型的字段来解决这个问题,但这看起来不优雅,而且对于类型来说太宽泛了!

最佳答案

方法toString来自java.lang.Object,它是Java中每个类隐式扩展的类。 Scala 中的 Any 类型会转换为 Java 的 Object

我们可以利用这一点并在 NodeIdentifier 中创建字段 value:Any 并使用它来提供 asString 的实现:

sealed trait NodeIdIdentifier {
    def value: Any

    def asString: String = value.toString
}

case class NumericTwoByteIdentifier(value: Byte) extends NodeIdIdentifier {}

case class NumericFourByteIdentifier(value: Short) extends NodeIdIdentifier {}

case class NumericIdentifier(value: Int) extends NodeIdIdentifier {}

case class StringIdentifier(value: String) extends NodeIdIdentifier {}
StringIdentifier("hello").asString //"hello"
​
NumericIdentifier(100).asString //"100"

当然,我们也可以让NodeIdIdentifier采用类型参数:

sealed trait NodeIdIdentifier[T] {
    def value: T

    def asString: String = value.toString
}

case class NumericTwoByteIdentifier(value: Byte) extends NodeIdIdentifier[Byte] {}

case class NumericFourByteIdentifier(value: Short) extends NodeIdIdentifier[Short] {}

case class NumericIdentifier(value: Int) extends NodeIdIdentifier[Int] {}

case class StringIdentifier(value: String) extends NodeIdIdentifier[String] {}

关于scala - 在子类中生成字符串实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57888834/

相关文章:

嵌套类的 json 编写器

scala - 带有 akka-cluster 的 akka-streams

scala - Spark 斯卡拉: Split each line between multiple RDDs

scala - 使用来自 JSON 字符串的嵌套映射

scala - MVar 公平性保证?

java - 无响应的actor系统: ThreadPoolExecutor dispatcher only creates core thread pool,显然会忽略最大线程池大小

scala - 如何从 HDFS 获取目录名称

scala - 如何在多个字段上动态排序 scala 列表

eclipse - 为什么 Scala `var` 在 Eclipse 中以红色突出显示

scala - Scala 中的列表串联操作