且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Scala:将字符串数组解析为案例类

更新时间:2023-11-02 22:04:52

您可以按照以下步骤进行操作(我以简化示例为例)

You can proceed as below (I've taken simplified example)

给出您的案例类别和数据(行)

Given your case class and data (lines)

// Your case-class
case class MyCaseClass(
  fieldByte: Byte,
  fieldString: String,
  fieldDouble: Double
)

// input data
val lines: List[String] = List(
  "1,AA,$1.1",
  "2,BB,$2.2",
  "3,CC,$3.3"
)






注意:您可以从文本文件 as

val lines = Source.fromFile("my_file.txt").getLines.toList






您可以使用一些实用的映射方法(清理和放大) ;解析)


You can have some utility methods for mapping (cleaning & parsing)

// remove '$' symbols from string
def removeDollars(line: String): String = line.replaceAll("\\$", "")

// split string into tokens and
// convert into MyCaseClass object
def parseLine(line: String): MyCaseClass = {
  val tokens: Seq[String] = line.split(",")
  MyCaseClass(
    fieldByte = tokens(0).toByte,
    fieldString = tokens(1),
    fieldDouble = tokens(2).toDouble
  )
}






然后使用它们将字符串转换为案例类对象


And then use them to convert strings into case-class objects

// conversion
val myCaseClassObjects: Seq[MyCaseClass] = lines.map(removeDollars).map(parseLine)






作为更高级(广义)方法,您可以生成映射(解析)函数,使用 reflection 之类的东西将令牌转换为案例类的字段,如此处


As a more advanced (and generalized) approach, you can generate the mapping (parsing) function for converting tokens into fields of your case-class using something like reflection, as told here