是否有一种优雅的方法将案例类转换为CSV值。
例如-
case class Person( name : String, age : Int, gender: String, address : Option[String])
我当时在考虑使用宏,但想知道是否还有其他选择。
注意:案例类不包含任何用户定义的字段。
implicits
和productIterator
怎么样?
implicit class CSVWrapper(val prod: Product) extends AnyVal {
def toCSV() = prod.productIterator.map{
case Some(value) => value
case None => ""
case rest => rest
}.mkString(",")
}
Person("name", 30, "male", None).toCSV()
product-collections也会为您生成csv。产品集合可很好地扩展;它是无反射的,并且与scala-js兼容。
import com.github.marklister.collections.io._
case class Foo(a:Int,b:String)
Seq(Foo(1,"hello"),Foo(2,"World")).csvIterator.mkString("\n")
res2: String =
1,"hello"
2,"World"
我是产品系列的作者
要完成已接受的答案,您还可以将产品类型与模式匹配进行匹配:
implicit class CSVWrapper(val prod: Product) extends AnyVal {
def toCSV: String = prod.productIterator.map{
case p: Product => p.toCSV
case rest => rest
}.mkString(",")
}
这将适用于嵌入式案例类:
case class Address(street: String, town: String, country: Option[String])
case class Person( name : String, age : Int, gender: Option[String], address : Option[Address])
Person("myname", 30, Some("male"), Some(Address("mystreet", "city", None))).toCSV
// result :
// myname,30,male,mystreet,city,