我们想格式化以下字符串:
(1854288750,binance,live),(1854288751,bitrix,live)
到 Scala 中的以下案例类:
case class Account(login :String, platform: String, type: String)
这是最有效的方法,因为我们不想使用 replaceAll
答案 0 :(得分:3)
您可以使用模式匹配
case class Account(login :String, platform: String, aType: String)
object Application extends App {
//parse single string
def parse(input: String): Option[Account] = {
if (!input.startsWith("(") || !input.endsWith(")"))
return None
//split input to list using separator
input.substring(1, input.length).split(",").toList match {
//if format is correct return instance of your data class
case List(login, platform, aType) => Some(Account(login, platform, aType))
case _ => None
}
}
//parse list of strings
def parse(input: List[String]): List[Account] =
input.map(parse).flatMap(_.toList)
println(parse("(1854288750,binance,live)"))
println(parse("(1854288751,bitrix,live)"))
val input: List[String] = List("(1854288750,binance,live)", "(1854288751,bitrix,live)", "abc",
"(1854288750,binance,live", "1854288750,binance,live)")
//two-elements list
println(parse(input))
}