Reputation: 1692
I am reading a CSV file with many columns and turning every row into an object. It goes like this:
val sighting = Sighting(
cols(0).toInt,
cols(1),
cols(2),
cols(3),
cols(4),
cols(5).toInt,
cols(6),
cols(7),
cols(8),
cols(9).toDouble
cols(10),
cols(11),
cols(12))
This looks seriously ugly to me. Short of named parameters (which would be an improvement, granted), is there anything I can do to make it look less ugly?
Upvotes: 1
Views: 62
Reputation: 1251
You can transfer the ugliness into a constructor which accepts an Array
. I am aware that this doesn't reduce the level of ugliness, however still a better place to handle.
object Sightings{
def apply(array: Array[String]): Sightings = new Sightings(array(0), array(1), ...)
}
Then you can use:
val strings: Array[String] = line.split(",") //split the line and convert it into array of strings
val sightings: Sightings = Sightings(strings) //create Sighting from the array
Upvotes: 0
Reputation: 795
How about this:
val sighting = cols match { case Seq(c0, c1, c2, ..., c12) =>
Sighting(c0.toInt, c1, c2, ...)
}
Upvotes: 2