I want to split a string delimited by commas and use the result as either a Seq
or a Set
:
def splitByComma(commaDelimited: String): Array[String]
= commaDelimited.trim.split(',')
def splitByCommaAsSet(commaDelimited: String): Set[String]
= splitByComma(commaDelimited).toSet
def splitByCommaAsSeq(commaDelimited: String): Seq[String]
= splitByComma(commaDelimited).toSeq
val foods = "sushi,taco,burrito"
val foodSet = splitByCommaAsSet(foods)
// foodSet: scala.collection.immutable.Set[String] = Set(sushi, taco, burrito)
val foodSeq = splitByCommaAsSeq(foods)
// foodSeq: Seq[String] = List(sushi, taco, burrito)
However, this is quite repetitive. Ideally, I would want to have something like genericSplitByComma[Set](foods)
that just returns a Set
when I pass Set
in, and returns a Seq
when I pass Seq
.