What is the most efficient way to create a Set from a string like this
val string = "Set(1,3,3,4,5)"
val mySet = string.toSet[Int]
res0: Set[Int] = Set(1,3,4,5)
I want to create this toSet method.
What is the most efficient way to create a Set from a string like this
val string = "Set(1,3,3,4,5)"
val mySet = string.toSet[Int]
res0: Set[Int] = Set(1,3,4,5)
I want to create this toSet method.
implicit class StringWithToIntSet(val self: String) extends AnyVal {
def toIntSet: Set[Int] = {
val Re = """Set\((.*)\)""".r
self match {
case Re(inner) => inner.split(",").map(_.toInt).toSet
}
}
}
Then:
scala> "Set(1,3,3,4,5)".toIntSet
res0: Set[Int] = Set(1, 3, 4, 5)
Note:
toSet because String already has a toSet method (that creates a Set[Char])toIntSet might not be a good candidate for an implicit as it will probably only be used in just one place. A simple private method would just add 1 extra character: toIntSet("Set(1,3,3,4,5)"). For me the added confusion of where the method comes from might be too much. On top of that I do not think toIntSet feels right on a String since it requires the String to have certain content. This however is very personal I guess. A side note: the implementation will fail if the pattern does not match.