score:0
based on the answer provided by @jwvh above,
i have come up with a solution which is working for me now:
val student_1 = student(
id = some("1"),
name = some("john"),
address = some(seq(
address(some("newyork"),some("usa")),
address(some("berlin"),some("germany")),
address(some("tokyo"),some("japan"))
)),
phone = some(seq(
"1111","9999","8888"
))
)
def csvheaders:list[string] = {
list("studentid","name","address.city","address.province","phones")
}
def tocsv:list[list[string]] ={
val maximumlength = address.getorelse(seq.empty[address]).length max 1
//phone.getorelse(seq.empty[string]).length for earlier case where phones were kept in separate rows , done by @jwvh above
val idlist = list.tabulate(maximumlength)(k => " ").updated(0,id.getorelse(""))
val namelist = list.tabulate(maximumlength)(k => " ").updated(0,name.getorelse(""))
val addresscitylist = if(address.isdefined){
address.get.map{
k => k.city.getorelse(" ")
}.tolist.padto(maximumlength," ")
} else{
list.tabulate(maximumlength)(k => " ")
}
val addressprovincelist = if(address.isdefined){
address.get.map{
k => k.province.getorelse(" ")
}.tolist.padto(maximumlength," ")
} else{
list.tabulate(maximumlength)(k => " ")
}
val phonelist = if(phone.isdefined){
list.tabulate(maximumlength)(k => " ").updated(0,phone.get.padto(maximumlength," ").mkstring("/"))
} else{
list.tabulate(maximumlength)(k => " ")
}
val transposedlist:list[list[string]] = list(idlist,namelist,addresscitylist,addressprovincelist,phonelist).transpose
transposedlist.+:(csvheaders)
}
so, now student_1.tocsv will return:
/* list(
list(studentid, name, address.city, address.province, phones),
list(1, john, newyork, usa, 1111/9999/8888),
list( , , berlin, germany, ),
list( , , tokyo, japan, )
) */
score:1
in this i simplified your address
type to just a string
, and i kept the phone
layout as you had it originally (i.e. the one i complained about in the comments). so this is more of a proof-of-concept rather than a finished product.
val student = student(some("1")
, some("john")
, some(seq("newyork", "berlin", "tokyo"))
, some(seq("1111","9999"))
)
student match {
case student(i,n,a,p) =>
val maxlen = a.getorelse(seq("")).length max p.getorelse(seq("")).length
seq( seq(i.getorelse("")).padto(maxlen,"")
, seq(n.getorelse("")).padto(maxlen,"")
, a.getorelse(seq()).padto(maxlen,"")
, p.getorelse(seq()).padto(maxlen,"")
).transpose
}
// res0: seq[seq[string]] = list( list(1, john, newyork, 1111)
// , list(, , berlin, 9999)
// , list(, , tokyo, ))
Source: stackoverflow.com
Related Query
- How to write a toCSV method for scala case class that would generate the csv string for the class?
- How can I view the code that Scala uses to automatically generate the apply function for case classes?
- How to write copy() method for Simple Class in Scala
- How to access a Java static method from Scala given a type alias for that class it resides in
- Scala spark: how to use dataset for a case class with the schema has snake_case?
- How do I write a scala extractor for a case class with default parameters?
- How to generate values for case class parameters in scala
- Play 2.1(scala) - How to write Format[T] for scala enumeration case class
- How do I write a query for mongodb using the casbah driver for scala that uses a substring and checks if the field is in a list of supplied values?
- How would I write a method to turn a binary search tree (BST) into a sorted list for the values in the BST?
- how can I use the copy method for case classes on a list of that case class?
- How to parse a csv with matching case class and store the output to treemap[Int, List[List[InputConfig]] object in scala
- scala - equivalent case class for the text parsing that has dynamic number of fields
- How to get around the Scala case class limit of 22 fields?
- Scala 2.10 reflection, how do I extract the field values from a case class, i.e. field list from case class
- How to specify schema for CSV file without using Scala case class?
- How do I write a JSON Format for an object in the Java library that doesn't have an apply method?
- How to write a Play JSON writes converter for a case class with a single nullable member
- How to write a zipWith method that returns the same type of collection as those passed to it?
- How do I create an explicit companion object for a case class which behaves identically to the replaced compiler provided implicit companion object?
- What happens to a variable assignment when I call a method that returns an instance of a case class holding the said variable?
- How to convert the Scala case class definition to Haskell?
- scala: how to create a generic type which is subtype of all the number classes in scala so that it can include compare method
- java.lang.NoSuchMethodException for init method in Scala case class
- How can I get random data generated for scala case classes with the ability to "change some values" for unit testing?
- How to implement a trait with a generic case class that creates a dataset in Scala
- How can provide JsonFormats for case class that references itself?
- How to write case class for enum column in Apache Spark Dataset?
- How the Nil is recognized in Scala as a method in List class
- toString method for inherited case class in Scala
More Query from same tag
- Using a mocked object as an implicit in scala using scalamock
- `val (A) = (3)` is correct, but `val (A,B)=(2,3)` can't be compiled, why?
- Function which generically takes a type and returns the same type
- How do I create a generic Scala function that returns an object based on the generic type?
- Is it possible in Scala to create a partial curried function using an anonymous function
- QueryStringBinder for List[String]
- Converting Postgres PGObject to JsValue in Anorm
- monad transformers in cats scala
- How to keep a groupedby list sorted in Play Framework 2 templates
- Multiple scala directories in sbt project with intelliJ-IDEA
- IntelliJ can't detect main.scala.html indexation
- How do I tell spray-json on Akka HTTP to "assume application/json"?
- Intellij: "Error running Scala Console: Cannot Start Process"
- Scala typeclass and implicit puzzle
- Failed to build request: attribute named is defined
- How do you add a file as a param in scalaj-http for a multipart/form-data request?
- How would I convert spark scala dataframe column to datetime?
- Scala Presentation Compiler - Minimal Example
- :: method in List - contravariant argument type
- Single iteration => Multiple output collections from Java to Scala
- IBM Tone Analyzer (plan Beta )is not working with this example
- How to use a `universe.Tree` created and type-checked in one Scala macro execution, in another macro execution?
- Scala: Implementing map and withFilter in a simple custom type
- Upsert into table using Merge for Scala for Scala using Databricks
- How to search through struct in Spark 2?
- How do I document vals in pattern definitions
- How to integrate Prometheus Metrics Middleware with http4s DSL service
- Scala Play evolutions not being applied
- Scala + Play: serialize Map to Json Array
- "Select In" using Slick