【问题标题】:How to do this with Scala generic如何使用 Scala 泛型做到这一点
【发布时间】:2012-08-04 06:11:04
【问题描述】:

目前我有几个非常相似的方法,我想将它们合并为一种方法。这里有两种方法

  def toInt(attrType: String, attrValue: String): Int = {
    attrType match {
      case "N" => attrValue.toInt
      case _ => -1
    }
  }

  def toString(attrType: String, attrValue: String): String = {
    attrType match {
      case "S" => attrValue
      case _ => ""
    }
  }

我认为在 Scala 中使用泛型有更简单的方法吗?

【问题讨论】:

  • 问题是:你想简化什么?在这个例子中,唯一有重复代码的是attrType match {。其余的要不同以使其更通用。
  • 实际代码比我展示的要复杂,我为问题简化了。

标签: scala


【解决方案1】:

您可以执行以下操作:

trait Converter[T] {
  def convert(attrType: String, attrValue: String): T
}

object ConverterTest {

  implicit object IntConverter extends Converter[Int] {
    def convert(attrType: String, attrValue: String): Int = {
      attrType match {
        case "N" => attrValue.toInt
        case _ => -1
      }
    }
  }

  implicit object StringConverter extends Converter[String] {
    def convert(attrType: String, attrValue: String): String = {
      attrType match {
        case "S" => attrValue
        case _ => ""
      }
    }
  }

  def to[T: Converter](attrType: String, attrValue: String): T = {
    implicitly[Converter[T]].convert(attrType, attrValue)
  }

  def main(args: Array[String]) {
    println(to[String]("S", "B"))
    println(to[String]("N", "B"))

    println(to[Int]("S", "23"))
    println(to[Int]("N", "23"))
  }
}

它的代码更多,我无法让类型推断起作用,所以它的用途可能有限。

但它是一个方法加上一堆转换器,可以在调用现场进行控制,因此您可以获得一些额外的灵活性。

值得付出努力吗?视实际用例而定。

【讨论】:

  • 英勇的努力,但正如你所说,是否值得努力,可能不值得。谢谢。
猜你喜欢
  • 1970-01-01
  • 2019-09-19
  • 2019-04-30
  • 2017-09-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多