如何在Scala中从字符串创建Set

Dan*_*ier 0 scala set

从这样的字符串创建Set的最有效方法是什么

val string = "Set(1,3,3,4,5)"

val mySet = string.toSet[Int]
res0: Set[Int] = Set(1,3,4,5)
Run Code Online (Sandbox Code Playgroud)

我想创建这个toSet方法.

dhg*_*dhg 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
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

然后:

scala> "Set(1,3,3,4,5)".toIntSet
res0: Set[Int] = Set(1, 3, 4, 5)
Run Code Online (Sandbox Code Playgroud)

注意:

  • 你不能调用它,toSet因为String已经有一个toSet方法(创建一个Set[Char])