I have a very simple case class called FooPosition:
case class FooPosition(x: Int, y: Int)
and a Foo
class that has a FooPosition
. I am interested in creating a function that returns -1 only for coordinates that are equal to (x-1, y)
with respect to a Foo
object and returns 0 everywhere else. So I wrote:
class Foo(position: FooPosition) {
def bar = (p: FooPosition) => p match {
case FooPosition(position.x - 1, position.y) => -1
case FooPosition(_, _) => 0
}
}
which results in an error that says "Not found: value -". Interestingly,
val myFoo = FooPosition(1, 0)
val newFoo = FooPosition(myFoo.x - 1, myFoo.y)
works just fine. I'm obviously missing something about pattern matching here (since I am a beginner). But what would be an elegant solution to this problem? I have worked around the problem using
class Foo(position: FooPosition) {
private val left = FooPosition(position.x - 1, position.y)
def bar = (p: FooPosition) => p match {
case `left` => -1
case FooPosition(_, _) => 0
}
}
but I think there must be a better way.
Thanks in advance.