Java's method priority rules are part of the reason why pattern matching works the way it does.
Say you had code that you wrote in the past 30 years that looks like this
public class Example{
public static void main(String[] args){
Number i = 3;
if (i instanceof Integer) {
doTask(i);
}
}
public static void doTask(Integer i){
System.out.println("integer");
}
public static void doTask(Number i){
System.out.println("number");
}
}
This will output number
even though i
is an Integer
because the stated type of i
is Number
.
In other languages like kotlin, if you check if i
is an Integer
, within the block of that if it will be considered an integer by the compiler.
Since java has legacy code that might have done something like this, you have to explicitly name a variable that will be considered an Integer
after the check
Number number = 3;
if (number instanceof Integer integer) {
doTask(integer); // will select the integer overload
doTask(number); // will select the number overload
// integer and number both refer to the same object
// so this will output true
System.out.println(integer == number);
}
While this might feel like a nuisance, structuring the language feature like this enables more generic "pattern matching" syntax that you can read about here (coming in the next few years) https://openjdk.java.net/jeps/405