resueman
resueman

Reputation: 10623

Pattern matching using current object

I'm trying to match an Option, and test to see if it's a Some containing the object making the call. So the code I want to write looks like this:

methodReturningOption() match {
    case Some(this) => doSomething()
    case _ => doSomethingElse()
}

but that fails to compile, with the error

'.' expected but ')' found

I also tried using Some(`this`) which gives the error

not found: value this

I can make it work if I add a variable which refers to this

val This = this
methodReturningOption() match {
    case Some(This) => doSomething()
    case _ => doSomethingElse()
}

but that looks ugly and seems like an unpleasant workaround. Is there an easier way to pattern match with this as an argument?

Upvotes: 0

Views: 269

Answers (2)

James Davies
James Davies

Reputation: 9869

It looks like this is considered a special keyword and can't be used in that context.

Jack Leow's solution is probably the best - I'd recommend going with that since it's much more explicit. However as an alternative you can also create a variable point to 'this' using the following syntax. (Note the self => on the first line)

class Person { self =>
    def bla() = methodReturningOption() match {
        case Some(`self`) => ???
        case _          => ???
    }
}

This doesn't really answer the question, it's just a potential alternative syntax that may be useful to you.

Upvotes: 1

Jack Leow
Jack Leow

Reputation: 22497

I suppose you could try this:

methodReturningOption() match {
  case Some(x) if x == this => doSomething()
  case _ => doSomethingElse()
}

Upvotes: 4

Related Questions