[solved]How to use variables in overriden method? is that possible?

def moveAllOccurancestoEnd(numbers: Array[Int], number: Int) {



    implicit val order = new Ordering[Int] {
      override def compare(x: Int, y: Int): Int =
        (x, y) match {

          case (number, _) => 1
          case (_, number) => -1
          case _        => 0

        }
    }


    numbers.sortInPlace



  }

How to use “number” variable inside override def compare(x: Int, y: Int): Int.

When i use some number like “0” or “1” in place of “number” i’m getting the required result…But when i kept “number” variable…I’m not getting the required result.
Is that allowed?

The problem is that you are introducing another variable called number in your pattern matches.

That also becomes apparent since you will receive that warning from the compiler:

[warn] main.scala:13:31: unreachable code
[warn]           case (_, number) => -1
[warn]                               ^
[warn] one warning found

which is because your first match clause matches anything and the later clauses will be ignored.

If you want to match on the value of the number variable given as parameter, you have to use backticks which inhibits binding a new variable:

        (x, y) match {
          case (`number`, _) => 1
          case (_, `number`) => -1
          case _        => 0
        }

BTW, procedure syntax is deprecated, you should use

def moveAllOccurancestoEnd(numbers: Array[Int], number: Int): Unit = {
  ...
}
1 Like

Thank you so much for helping me and I have learned some new points.