Reputation: 8494
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?
Upvotes: 1
Views: 97
Reputation: 81862
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.
Upvotes: 3