0

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.

1
  • Does efficient mean "my time is valuable" or "this runs on my google enabled eyewear so I can't run the compiler to do it"? Commented Feb 4, 2014 at 20:18

1 Answer 1

5
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])
Sign up to request clarification or add additional context in comments.

2 Comments

Are there any occasions in which you would not use an implicit for a simple case like this? I usually think of using implicits for cases where their addition in complexity, and obscuration of the location of the method, is more than offset by the simplification of many points of use. This usage, in contrast, looks compulsive to me - "someone with a hammer", as it were. You've obviously done a heck of a lot more Scala than me, though!
I agree that the 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.

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.