François Beausoleil
François Beausoleil

Reputation: 16515

Is Scala's match an expression or not?

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?

Upvotes: 3

Views: 188

Answers (1)

Philippe
Philippe

Reputation: 9752

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 (SimpleExpr in the grammar), and match expressions are not in that subset (neither are if expressions, for instance).

As a result, you need to put parentheses around them:

(service match {
  case => ...
  ...
}).isDefined

This question has some more answers.

(Edited to incorporate some comments.)

Upvotes: 10

Related Questions