Reputation: 25269
Lets say I have something like this:
def f () = {
var v = someLookupToV()
match v {
case Some(v) => (v.id, someOtherLookup(v.id))
case None => None // <<-- doesn't work, but I'm not sure what to put there!
}
}
Sort of assuming that someLookupToV returns some object, that has a field id, and then I have some other lookup based on v.id. I want to return both values as a tuple. But what do I do if Some(v) doesn't match anything? What do I return? None and (None,None) didnt' work. Scala accepted (null,null) but I've got no clue if that's the right thing to do...
Upvotes: 2
Views: 1818
Reputation: 5919
I would not have the function return (Int, Option[Int])
, but instead Option[(Int, Option[Int])]
:
def f = someLookupToV match {
case Some(v) => Some(v.id, someOtherLookup(v.id))
case None => None
}
or, somewhat shorter:
def f = someLookupToV.map(v => (v.id, someOtherLookup(v.id)))
Upvotes: 15
Reputation: 2055
If you want to return (None, None), your "case Some" line needs to return a tuple of (Option, Option).
As written in your example, your case Some
is returning (Int, Option). That's assuming your v.id
is an Int and someOtherLookup returns an Option.
Upvotes: 1