Thursday, May 21, 2015

more Java 8 Goodies

I did streams yesterday but lets touch on a couple fun points.  Again I am a little late to the party on this stuff but I doubt I am the only one.


Optional 


      Could this be the end of null pointer exceptions?  This is a lot nicer way to default values and do null checks.  If you follow my blog you know I hate ternary operators due to their poor readable and this does away with that in the case of default values.



    Optional<String> displayText = Optional.ofNullable(null);
    System.out.println(
        "display text found? " + displayText.isPresent() );
    System.out.println(
        "display text: " + displayText.orElseGet( () -> "n/a" ) );
    System.out.println(
        displayText.map( text -> text.toUpperCase() ).orElse(" ") );


Interface Changes

      I am not entirely sure about this one because the line between abstract class and interface is really blurry.

Default Methods:

      This can help with backwards comparability when adding new methods to interfaces.


    public interface MouseTrap {
 // ...
 default void setTrap() {
     // ...
 }
     }

Static Methods:


    private interface MouseTrapFactory {
        // Interfaces now allow static methods
        static MouseTrap createMouseTrap(String bait) {
        return new BetterMouseTrap(bait);
    }


Native JavaScript Support

    Since I haven't used it really yet I don't want to just copy other peoples examples but now with Java 8 the native Javascript engine that can be accessed with in is Nashorn (pr. "nass-horn").  The JavaScript you write can be executed from the command line (which can even call Java classes) or within Java classes.





Related Content



No comments:

Post a Comment