goralph
goralph

Reputation: 1086

Handling Option[A] where function takes A as a parameter

I have a case class Foo which has a field baz: Option[List[Bar]].

Also, I have a function - def f(baz: List[Bar])

I need to pass the List[Bar] to f().

What would be the best way to do this?

Upvotes: 1

Views: 111

Answers (2)

wheaties
wheaties

Reputation: 35970

Option is great because it forces you to come to grips when there is no item. In the case of a List, Option may be overkill as there already exists a corresponding empty, i.e. they are both Monads:

f(myOptList getOrElse Nil)

wherein I'd say you should probably only have a List ever. Otherwise you deal with a trinary case: Something that is empty, something that has items and empty.

Upvotes: 4

Ende Neu
Ende Neu

Reputation: 15773

case class Baz(b: Int)
case class Foo(bazs: Option[List[Baz]])

val foo = Foo(Option(List(Baz(1), Baz(2))))
foo.bazs.map(list => f(list))

Option is a monad, if it's a Some the map will we applied to it, else if it's a None nothing will happen, from the REPL:

scala> def f(b: List[Baz]) = b.foreach(println)
f: (b: List[Baz])Unit

scala>     foo.bazs.map(list => f(list))
Baz(1)
Baz(2)
res1: Option[Unit] = Some(())

scala> val foo = Foo(None)
foo: Foo = Foo(None)

scala>     foo.bazs.map(list => f(list))
res2: Option[Unit] = None

Upvotes: 2

Related Questions