문제

I've got a CSV response from a service and I want to generate a list of case classes. For example:

case class MyCaseClass(e1: String, e2: String, e3: String)

val body = getLargeCsvFromServiceOrSomething()
val elements = body.split(",")

Now I have an Array[String]. I want to take that large array and break it down into 3 element chucks, so I can generate my List[MyCaseClass], where each instance take 3 elements from the array. Is there a method similar to splitAt, but spits every n elements? I'm sure I can do this point-free, but it's just not coming to me.

도움이 되었습니까?

해결책

What you want is grouped:

scala> List(1,2,3,4,5,6,7).grouped(3).toList
res0: List[List[Int]] = List(List(1, 2, 3), List(4, 5, 6), List(7))

So your thing might be like:

val elements = Array("a","b","c","d","e","f")
val classes = elements.grouped(3).map{ case Array(a,b,c) => MyCaseClass(a,b,c) }    
println(classes.toList) // List(MyCaseClass(a,b,c), MyCaseClass(d,e,f))
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top