Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scala converting Array[String] to case class

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.

like image 455
nir Avatar asked May 01 '15 23:05

nir


1 Answers

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")
like image 125
elm Avatar answered Nov 10 '22 04:11

elm