Reputation: 2661
I am new to Scala and I am trying to get all attribute values of "Lr" type in a tab separated format. However, whenever I am executing "Echo" as below the program is returning :
Some(something1) Some(something2)
Whereas, I am expecting :
something1 something2
Any clue on how to modify my code to get my expected format?
package com.......
case class Lr (
some1_ID : Option[String],
some2_ID : Option[String]
)
{
def getData(): String =
{
return productIterator.mkString("\t")
}
}
object Echo {
def main( args:Array[String] ):Unit =
{
val testLR = Lr(Option("something1"),Option("something2"))
print(testLR.getData())
}
}
Upvotes: 1
Views: 1116
Reputation: 1428
It depends on what do you want to do in case some attribute is None.
If you want to discard None
case class Lr (some1_ID : Option[String], some2_ID : Option[String]) {
def getData: String = {
Seq(some1_ID, some2_ID).flatten.mkString("\t")
}
}
If you want to use an alternative value
case class Lr(some1_ID : Option[String], some2_ID : Option[String]) {
def getData: String = {
Seq(some1_ID, some2_ID).map(_.getOrElse("XXX")).mkString("\t")
}
}
If you want to use productIterator, it is a Iterator[Any], so you need pattern matching in order to work with Options.
case class Lr(some1_ID : Option[String], some2_ID : Option[String]) {
def getData: String = {
productIterator.collect {
case Some(value) => value
// case None => "ALTERNATIVE VALUE"
// case others => others (non Option fields)
}.mkString("\t")
}
}
Upvotes: 6
Reputation: 262514
What do you want to print for None
? Decide that, then you can do something like
def getData: String =
Seq(
some1_ID.getOrElse("-"),
some2_ID.getOrElse("-")
).mkString("\t")
Upvotes: 1