1

Currently I have couple of methods that are very similar and I would like to merge them into 1 method. Here are the 2 methods

  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 _ => ""
    }
  }

I am thinking there is an easier way to do this in Scala using generic?

Bob
  • 8,424
  • 17
  • 72
  • 110
  • The question is: What do you want to simplify? In this example, the only thing which has code duplicates is the `attrType match {`. The rest is to different to make it more generic. – kiritsuku Aug 04 '12 at 10:01
  • The actual code is more complicated than what I showed, I simplified it for the question. – Bob Aug 05 '12 at 05:35

1 Answers1

3

You could do the following:

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

Its more code, and I couldn't get type inferencing to work, so it is probably of limited use.

But it is a single method plus a bunch of converters that can get controlled at the call site, so you get some extra flexibility.

Is it worth the effort? Depends on the actual use case.

Jens Schauder
  • 77,657
  • 34
  • 181
  • 348