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, ))

Related Query

More Query from same tag