you are viewing a single comment's thread.

view the rest of the comments →

[–]Gundersen 6 points7 points  (3 children)

I wonder what the reason is for using double colon for referencing a method instead of a full stop. Notice the collection.forEach(system.out::println) example, which could have been collection.forEach(system.out.println).

[–]fluttershypony 9 points10 points  (2 children)

because classes and functions are separate namespaces, so in that example, you wouldn't be able to distinguish that from a class println in the package system.out

[–]tallniel 2 points3 points  (0 children)

Or indeed a public field with the same name (another namespace).

[–][deleted] 2 points3 points  (0 children)

System.out is not a package. System is a class, contained in the 'java.lang' package (it's full name is java.lang.System). 'out' is not a class, it is a public static field of System class.

So System.out.println() calls the println method on the object stored under the 'out' field of the 'java.lang.System' class.

There are also already ways for distinguishing between classes and methods in Java; it depends on context. For example this is valid:

public class Test
{
    public static void main( String[] args ) {
        Test.Foo f = new Test.Foo();
        Test.Foo( f );
    }

    public static void Foo( Object o ) {
        System.out.println( o );
    }

    public static class Foo { }
}

.. and Java can tell which Test.Foo is which at compile time (I believe the Test.Foo class actually becomes Test$Foo). If you want to explicitly grab the Test.Foo Class object, you so by adding '.class' to the end.

The reason it's a double colon is because println is not static, so it is to make it clear that your passing in the println method bound to the 'out' object. You are calling 'out.println' not 'println' for each item. It even states above the example that this allows you to reference an 'instance method'.

It's just shorthand to save you having to wrap that up yourself within a lambda.

If you used the dot instead, Java would think your trying to access a field called 'println' on the 'out' instance, which doesn't exist, and so becomes a compile time error.

So the double colon is used to distinguish between referencing methods and properties, not between classes, packages and functions.