-3

I'm coming from a JavaScript background and I'm seeing the :: operator for the first time. I understand what it does, but I'm wondering why it's necessary. In JavaScript, something like this is perfectly valid:

[1, 2, 3].forEach(console.log);

There's no need for a new operator - I'm just not calling the log function directly/explicitly. So my question is, why doesn't that work in Java? What is there in Java that makes the Class.method unusable (masks it?!)?

NoBullsh1t
  • 483
  • 4
  • 14
  • `Class.method` could be referring to a field. Perhaps the designers wanted to avoid that ambiguity... – Sweeper Oct 10 '22 at 11:39
  • 1
    Because in Java, `console.log` refers to a variable (field). – Holger Oct 10 '22 at 11:39
  • In JavaScript functions are first-class objects, so you can simply pass them to a function as arguments. Java doesn't have such a thing, so it needs method references to emulate that. – QBrute Oct 10 '22 at 11:39
  • there are disadvantages in using that *notation*: reading that code I would need to search what `log` is... a method, a field, ... (at least for unknown objects/methods) – user16320675 Oct 17 '22 at 15:36
  • No you don't, if you know that forEach takes a function as an argument – NoBullsh1t Oct 18 '22 at 19:02
  • True. The trouble with weakly typed languages. That's why TypeScript is popular. No issues there – NoBullsh1t Oct 23 '22 at 08:33

1 Answers1

1

Because variables and methods do not share the same namespace in Java, so you can have variables and methods with the same name.

This is valid in Java:

class Test {
    private static int c;
    private static int c() { return 0; }
}

Now what would Test.c refer to here if we didn't have the :: operator?

Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95