Daniel Cukier
Daniel Cukier

Reputation: 11942

How to create a Set from a string in Scala

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.

Upvotes: 0

Views: 1749

Answers (1)

dhg
dhg

Reputation: 52681

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:

  • You can't call it toSet because String already has a toSet method (that creates a Set[Char])

Upvotes: 5

Related Questions