6

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.

1

1 Answer 1

6

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")
Sign up to request clarification or add additional context in comments.

4 Comments

I'd suggest naming this something other than apply (e.g. parse), since many people will expect apply to take the case class's members directly, and definitely not to fail with an exception on normal input.
@TravisBrown thanks, agree naming the method apply proves misleading (unintended semantics :) Please note update...
Thanks, looks reasonable to me (I'd still prefer the result as Try[ABC], but that's more a matter of taste).
ok so this demonstrate parsing logic in one place(object) but it doesn't buy much in my case as I iterate each file only once. I could just do ABC(arr(0).toInt, arr(1)). I agree elm suggestion is more object oriented and I will prefer that. But what I was looking for is straightforward way just to convert array's elements into case class in same order. i.e. arr(0) gets assign to first element of case class and so on. It should also do type conversion and throw compile or runtime error if it can't parse

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.