Reputation: 1827
I did "mkString" but still can not print list of strings. With input line:
9002194187,2644,54,100,3,4,2,5
I get the following output:
Line: 9002194187,2644,54,100,3,4,2,5
StrArr: 9002194187,2644,54,100,3,4,2,5
Lst: [Ljava.lang.String;@223d2e6c
Lst again: List([Ljava.lang.String;@223d2e6c)
Lst1: [Ljava.lang.String;@223d2e6c
Result: foo
From the code below:
def mkRecord(line: String) : String = {
val klass = "foo"
val strArr = line.split(",") // convert string to array of strings
println("Line: "+line)
println("StrArr: "+strArr.mkString(","))
val lst = List(strArr)
println("Lst: "+lst.mkString(" - "))
println("Lst again: "+lst)
val lst1 = lst.tail ++ List(klass) // attribute list except for the first one, plus new klass attribute
println("Lst1: "+lst.mkString(" , "))
val result = lst1.mkString(",") // attribute string
println("Result: "+ result)
return result
}
Please, help. I am at complete loss (
Upvotes: 0
Views: 624
Reputation: 4843
You can turn any array into a list with its toList
operator, avoiding this problem (the nature of which Shadowlands has explained). You can do string -> array -> list in one line:
line.split(',').toList
Using a collection's toList
method is often going to be faster than extracting all the elements into a sequence and then converting that sequence into a list, not least because you'll be using a method optimised for the source collection. However, that's an optimisation which you can worry about after the priorities of success and clarity.
Upvotes: 0
Reputation: 15074
The constructor for List (actually, the apply method on the List companion object) takes parameters in the form of scala's "varargs" equivalent:
def apply[A](xs: A*): List[A] // some irrelevant details have been elided
In java, this would be written something like:
public static List<A> apply(A... args)
In scala this can be called using any Seq (or subclass), but using a special notation. The line you used:
val lst = List(strArr)
creates a List[Array[String]]
, with a single entry - the array strArr. To tell the compiler to turn the array into a varargs when passing it to the List apply
method, add : _*
on the end (the space is optional):
val lst = List(strArr: _*)
This change in your code will result in:
scala> mkRecord(chkStr)
Line: 9002194187,2644,54,100,3,4,2,5
StrArr: 9002194187,2644,54,100,3,4,2,5
Lst: 9002194187 - 2644 - 54 - 100 - 3 - 4 - 2 - 5
Lst again: List(9002194187, 2644, 54, 100, 3, 4, 2, 5)
Lst1: 9002194187 , 2644 , 54 , 100 , 3 , 4 , 2 , 5
Result: 2644,54,100,3,4,2,5,foo
res1: String = 2644,54,100,3,4,2,5,foo
Upvotes: 2