I want to split a string delimited by commas and use the result as either a Seq
or a Set
:
def splitByComma(commaDelimited: String): Arr
@KrzysztofAtłasik's answer works great for Scala 2.12
.
This is a solution for 2.13
. (Not completely sure if this is the best way).
import scala.collection.Factory
import scala.language.higherKinds
def splitByComma[C[_]](commaDelimited: String)(implicit f: Factory[String, C[String]]): C[String] =
f.fromSpecific(commaDelimited.split(","))
// Or, as Dmytro stated, which I have to agree looks better.
commaDelimited.split(",").to(f)
Which you can use like this:
splitByComma[Array]("hello,world!")
// res: Array[String] = Array(hello, world!)
splitByComma[Set]("hello,world!")
// res: Set[String] = Set(hello, world!)
splitByComma[List]("hello,world!")
// res: List[String] = List(hello, world!)