newbie question but I often found myself working with files, parsing each line and convert it into case class so that I can use if further in more object like manner. In java and now in scala I do same procedure.
case class ABC(v1: Int, v2: String)
val str = line.split("\t")
val v1 = str(0).toInt
val v2 = str(1)
ABC(v1, v2)
Is there any shorter way I can create case class from array than this? This gets very tedious as I always have tons of fields to process.
Define an parse
method in a companion object that takes a string and extracts values for constructing an instance,
import util._
case class ABC(v1: Int, v2: String)
object ABC {
def parse(s: String): Try[ABC] = {
val Array(v1,v2,_*) = s.split("\t")
Try(ABC(v1.toInt, v2))
}
}
Note v1
is converted to Int
, also we extract the first two items from the split string yet any number of items may be extracted and then converted to desired types.
Then a valid use includes for instance
val v = ABC.parse("12\t ab")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With