从这样的字符串创建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方法.
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])