Java Magazine, Jan/Feb 2016
ORACLE COM JAVAMAGAZINE JANUARY FEBRUARY 2016 68 jvm languages Blocks aka closures In appearance Gosu blocks are similar to Java lambdas var list Pascal Java Gosu var lengths list map e e length As you can see Gosu blocks begin with a instead of Javas otherwise the syntax is nearly identical Under the hood however things are quite diferent For starters Gosu blocks are true closures Basically this means that they can access and modify any variables from the local scope But what really distinguishes a block from a lambda is that it has its own type the Function type There is no need for functional interfaces or SAMs as a go between in Gosu because the Function type is a first class type var capitalize String String s s capitalize or var capitalize s String s capitalize You can use Function types anywhere For instance you can use Function types directly in a functions parameter list function visitThings consumer Thing And you can use them with generics var listeners Set block Event Function types are 100 percent interoperable with Java 8 functional interfaces You can pass a block to a functional interface and pass a functional interface to a Function type Generics Gosu generics use array style covariance by default For instance the following assignment is legal in Gosu var list List Object new ArrayList String While this is technically unsound it works the way most programmers think So unlike Java Gosu does not have wildcards or any type of use site variance In our experience usesite variance is a significant source of confusion which leads to misuse and circumvention of generics via casting and other techniques Fundamentally type safety exists to help programmers read and write better code it shouldnt get in the way Alternatively if you dont want array style variance for your generic class you can make it fully typesafe using C style in out variance modifiers in your type variable declarations For instance typesafe Consumer and Producer interfaces can be defined like so interface Consumer in T function apply t T interface Producer out T function get T Generally stuff returned out of a function is covariant while stuff passed in to a function is contravariant Gosu verifies usage of in out type variables against a more sophisticated version of these basic rules Note that if you mix a default generic type with an in out type Gosu infers the variance of the default type and checks whether its compatible error T is used in an out position in Callable interface Listener in T extends Callable T function someEvent t T Here Gosu infers the variance of Callables T as out and reports the incompatibility Gosu infers variance of both Gosu and Java types including usage of wildcards inside Java types Another useful aspect of Gosu generics type arguments persist at runtime In technical speak Gosu employs type
You must have JavaScript enabled to view digital editions.