0

When I do str.split("\|") by default it returns Array[string]. How do i get return type as List[String] instead of Array[string]. I was able to convert to List using toList. But, I was wondering is it possible to get it without toList.

scala> val str = "a|b|c"
str: String = a|b|c

scala> val arr = str.split("\\|")
arr: Array[String] = Array(a, b, c)

scala> val convList = arr.toList
convList: List[String] = List(a, b, c)

scala> val lis: List[String] = str.split("\\|")
<console>:11: error: type mismatch;
found   : Array[String]
required: List[String]
val lis: List[String] = str.split("\\|")
3
  • 7
    what is the problem with toList? Remember, String is the java.lang.String and its split returns an array. Commented Sep 28, 2015 at 7:47
  • Thanks for response. Actually there were lot of array in full program but every where i wanted it to be List. Implicit conversion seems helpful Commented Sep 28, 2015 at 8:18
  • But implicit conversion is just syntactic sugar. It is still an array and you still call toList :) Commented Sep 28, 2015 at 10:28

1 Answer 1

1

You can implement an implicit conversion, then assignment will work without type error;

implicit def arrayToList[A](arr: Array[A]) = arr.toList
Sign up to request clarification or add additional context in comments.

2 Comments

Please don't do this. Implicit conversions are a bad idea in most cases (they now require a feature flag), and this conversion specifically is likely to make it much harder to reason about performance in your program. Just use toList, possibly via a helper method wrapping split.
Thank you for bringing out, can you give a detailed link for further readings? @TravisBrown

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.