Reputation: 137
I have an Option[List[String]] where I have several fields and want to create an object with them as parameters. Is there a way of doing this other than manually?
Details:
class Foo(var1: String, var2: String, var3: String)
I can't do
foo = new Foo(datarow)
And would rather not do
foo = new Foo(datarow.get(0), datarow.get(1), datarow.get(2))
Upvotes: 3
Views: 87
Reputation: 139058
There's a safe way to do this that's still pretty concise:
class Foo(var1: String, var2: String, var3: String)
val datarow = Option(List("a", "b", "c"))
val result: Option[Foo] = datarow.collect {
case v1 :: v2 :: v3 :: _ => new Foo(v1, v2, v3)
}
The combination of collect
and pattern matching on the first three elements of the list says "if this Option
isn't empty and if it contains a list with at least three elements, use them to instantiate the Foo
".
You end up with an Option[Foo]
, not a Foo
, but that's a small price to pay to avoid runtime errors because the Option
is empty or the list doesn't have enough elements.
Upvotes: 9