I’m confused with Scala’s syntax again. I expected this to work just fine:
// VERSION 1
def isInteractionKnown(service: Service, serviceId: String) = service match {
case TwitterService =>
twitterInteractions.findUuidByTweetId(serviceId.toLong)
case FacebookService =>
facebookInteractions.findUuidByServiceId(serviceId)
}.isDefined
NOTE: Both findUuidByTweetId and findUuidByServiceId return an Option[UUID]
scalac tells me:
error: ';' expected but '.' found.
}.isDefined
When I let my IDE (IDEA) reformat the code, .isDefined part ends up on a line of it’s own. It’s as if match isn’t an expression. But in my mind, what I did was functionally equivalent to:
// VERSION 2
def isInteractionKnown(service: Service, serviceId: String) = {
val a = service match {
case TwitterService =>
twitterInteractions.findUuidByTweetId(serviceId.toLong)
case FacebookService =>
facebookInteractions.findUuidByServiceId(serviceId)
}
a.isDefined
}
which parses and does exactly what I want. Why is the first syntax not accepted?
Yes, it is an expression. Not all expressions are equal, though; according to the Scala Language Specification, Chapter 6, “Expressions”, the receiver of a method invocation can only come from a (syntactical) subset of all expressions (
SimpleExprin the grammar), andmatchexpressions are not in that subset (neither areifexpressions, for instance).As a result, you need to put parentheses around them:
This question has some more answers.
(Edited to incorporate some comments.)