Notable differences between Gosu and Java

The following tables briefly summarize notable differences between Gosu and Java, with particular attention to requirements for converting existing Java code to Gosu. If the Gosu column contains multiple code examples, these examples show the multiple ways in which Gosu can represent the Java code in the Java column. If the Required Change? column contains “Required”, you must make this change to convert existing Java code to Gosu. If this column contains “Optional”, that item is either an optional feature, a new feature, or Gosu optionally permits the Java syntax for this feature.

The following table shows general differences between Gosu and Java.

General difference

Java

Gosu

Required change?

Omit semicolons in most code. Gosu supports the semicolon, but standard coding style is to omit it. One exception is in block declarations with multiple statements.

x = 1;
x = 1

Optional.

Print to console by using the print function. For compatibility with Java code that is converted to Gosu, you can optionally call the Java class java.lang.System print methods.

System.out.println("hello world");

Gosu style:

print("hello world")

Java compatibility style:

System.out.println("hello world")

Optional.

For Boolean operators, optionally use more natural English versions. Gosu also supports the symbolic versions that Java uses.

(a && b) || c

Gosu style:

(a and b) or c

Java compatibility style:

(a && b) || c

Optional.

Null-safe property accessor paths.

// Initialize to null
ArrayList<Windows> x = null 
// Check earlier parts of 
// path for null, to avoid 
// null pointer exception 
if (house != null and house.Walls != null) {
  x = house.Walls.Windows
}
var x = house.Walls.Windows

Optional. Do not make this change for cases in which you rely on throwing null pointer exceptions.

The following table shows the differences in functions and variables between Gosu and Java.

Function or variable difference

Java

Gosu

Required change?

In function declarations:

  • Use the keyword function.
  • List the type after the name, delimited by a colon, for parameters.
  • List the type after the parentheses that contain the parameters, delimited by a colon, for the return value.
public int addNumbers(int x, String y) {
...
}
public function addNumbers(x : int, y : String) : int { 
... 
}

Required

In variable declarations, use the var keyword. Typically, you can rely on Gosu type inference and omit explicit type declaration. To explicitly declare the type, list the type after the variable, delimited by a colon. You can also coerce the expression on the right side, which affects type inference.

Auto c = new Auto();
Type inference:
var c = new Auto()
Explicit:
var c : Auto = new Auto()
Type inference with coercion:
var c = new Auto() as Vehicle

Required

In declarations of variable argument functions, also called vararg functions, Gosu does not support the special Java syntax that indicates a variable number of arguments by using ... after the parameter type. Instead, design your methods to use arrays or collections.

  • To call variable argument Java functions, pass an array of the declared type.
  • To pass no values for the optional parameter, you can pass either an empty array {} or no value.
Note: Gosu array initialization syntax is useful for calling these types of methods.
This example demonstrates how to use a collection in a method declaration and call it using standard Gosu list initializer syntax:
static function setValues( preparedStatement: PreparedStatement, values: List<Object> )
MyClass.setValues( ps )
MyClass.setValues( ps, {} )
MyClass.setValues( ps, {value} )
MyClass.setValues( ps, {my, many, values} )
public String format(Object... args);
public String errorMessage(Object... args);

Method call using array initializer syntax:

var c = format({"aa","bb"})

Function declaration:

public function format(args : Object[]) : String

Method call with no arguments:

var e = errorMessage()

Required

Gosu supports the unary operator assignment statements ++ and --, with the following restrictions:

  • Only use the operator after the variable, such as i++ .
  • These operators form only statements, not expressions.

Gosu supports other compound assignment statements, such as +=, -=.

if (++i > 2) { 
  ...
}
i++
if (i > 2) { 
  ...
}

Required

In an inner class, referring to methods, fields, and properties in the outer class uses the keyword outer and does not require specification of the outer class name.

String oldId = MyOuterClass.this._id;
Gosu style:
var oldId = outer._id
Java compatibility style:
var oldId = MyOuterClass.this._id
If there is no ambiguity with an identifier in the inner class, you can omit the outer. syntax.
var oldId = _id

Optional

Calling a default method on an interface uses map-access operator syntax.
IJourney.super.travel();
super[IJourney].travel()
Required

The following table shows the differences in the type system between Gosu and Java.

Type system difference

Java

Gosu

Required change?

For coercions, use the as keyword.

Optionally, for compatibility, Gosu supports Java-style coercion syntax.

int x = (int) 2.1; 

Gosu style:

var x = 2.1 as int

Java compatibility style:

var x = (int) 2.1

Optional.

Gosu downcasts to a more specific type in if and switch statements. Omit casting to the specific type.

Object x = "nice";
Int sl = 0;
if (x instanceof String) {
  sl = ((String) x).length; 
}
var x : Object = "nice"
var sl = 0
if (x typeis String) {
  sl = x.length // Downcast
}

Optional.

Check if an object is a specific type or its subtypes by using typeis, which is similar to the Java instanceof operator.

myobj instanceof String;
myobj typeis String

Required.

To reference the type directly, use typeof. Direct comparisons to a type do not match on subtypes. Consider using typeis for this type of comparison rather than typeof.

myobj.class
typeof myobj

Optional.

In Gosu, type names are first-class symbols for the type. Do not get the class property from a type name.

Class sc = String.class;
var sc = String

Required.

Types defined natively in Gosu as generic types preserve their type information, including parameterization, at run time. This feature is called reified generics. In contrast, Java removes this information. This feature is called type erasure.

From Gosu, Java types lack parameterization even if instantiated in Gosu.

For native Gosu types, Gosu preserves type parameterization at run time.

ArrayList<String> mylist = new ArrayList<String>();
System.out.println(mylist.getClass);

This code prints:

class java.util.ArrayList

var mylist = new ArrayList<String>()
print(typeof mylist)

This code prints:

java.util.ArrayList<java.lang.Object>

Note that ArrayList is a Java type.

For native Gosu types as the main type, Gosu preserves the parameterization as runtime type information. In the following example, assume MyClass is a Gosu class:

var mycustom = new MyClass<String>()
print(typeof mycustom)

This code prints:

my.package.MyClass<java.lang.String>

Optional for typical use consuming existing Java types.

If your code checks type information of native Gosu types, remember that Gosu has reified generics.

Gosu generics support array-style variance of different generic types. In Java, this usage is a compilation error, even though it is natural to assume that it works.

In Java, this code causes a compilation error:

ArrayList<Object> mylist;
mylist = new ArrayList<String>();

The analogous Gosu code works:

var mylist : ArrayList<Object>
mylist = new ArrayList<String>()

Optional.

The following table shows the differences in defining classes between Gosu and Java.

Defining classes difference

Java

Gosu

Required change?

Declare that you use specific types or package hierarchies with the keyword uses rather than import.

import com.abc.MyClass;
uses com.abc.MyClass

Required

Declare that you use specific static type members with the keyword uses rather than import. Use the # symbol before the member name or * symbol, not the period (.) symbol.
import com.abc.MyClass.MY_CONST;
import com.abc.MyClass.*;
uses com.abc.MyClass#MY_CONST
uses com.abc.MyClass#*

Required

To declare one or more class constructors, write them as functions named construct but omit the keyword function. Gosu does not support Java-style constructors.

class ABC {
  public ABC(String id){
  }
}
class ABC {
  construct(id : String) {
  }
}

Required

The following table shows the differences in control flow between Gosu and Java.

Control flow difference

Java

Gosu

Required change?

The for loop syntax in Gosu is different for iterating across a list or array. Use the same Gosu syntax for iterating with any iterable object, which is an object that implements Iterable. Optionally, add index indexVar before the closing parenthesis to create a zero-based index variable. If the object to iterate across is null, Gosu skips the loop and does not throw an exception. Java does throw an exception in this case.

int[] numbers = { 1,2,3 };
for (int item : numbers) {
  ...
}
var numbers : int[] = {1,2,3}
for (item in numbers) {
  ...
}

Required

The for loop syntax in Gosu is different for iterating a loop for an integer number of times. The loop variable contains the zero-based index.

Gosu has native support for intervals, which are sequences of values of the same type between a given pair of end-point values. For example, the set of integers beginning with 0 and ending with 10 has the shorthand syntax 0..10. Intervals are useful for writing concise for loops.

Gosu does not support the for (initialize;compare;increment) syntax that Java uses. You can duplicate this syntax by using a while statement.

for (int i=1; i<20; i++){
  ...
}
for (item in 20) {
  ...
}

Using Gosu intervals:

for (i in 1..20) {
  ...
}

Verbose style:

var i = 0
while (i < 20) {
  ...
  i++
}

Required

The following table shows optional enhancements that Java does not support and that Gosu provides.

Difference

Java

Gosu

Required change?

Gosu enhancements, which support adding methods and properties to any type, including Java types.

Not applicable

enhancement StrLenEnhancement : java.lang.String {
  public property get PrettyLength() : String {
    return "length : " + this.length()
  }
}

Optional

Gosu blocks, which are in-line functions that act like objects. These blocks are especially useful with the Gosu collections enhancements. Blocks can also be useful as a shortcut for implementing one-method interfaces.

Not applicable

\ x : Integer -> x * x 

Optional

Native XML support and XSD support.

Not applicable

var e = schema.parse(xmlText)

Optional

Native support for consuming web services with syntax similar to native method calls.

Not applicable

extAPI.myMethod(1, true, "c")

Optional

Native String templates and file-based templates with type-safe parameters.

Not applicable

var s = "Total = ${ x }."

Optional

Gosu uses the Java-based collections APIs but improves upon them:

  • Simplified initialization syntax that preserves type safety.
  • Simpler array-like syntax for getting and setting values in lists, maps, and sets.
  • Additional methods and properties to improve functionality of the Java classes. Some enhancements use Gosu blocks for concise, flexible code.

For new code, use the Gosu style initialization and APIs. You can call the more verbose Java style for compatibility.

List<String> strs = 
new ArrayList<String>(
Arrays.asList(
  "a", "ab", "abc"
));

Simplified initialization:

var strs = {"a", "ab", "abc"}

Array-like "set" and "get":

strs[0] = "b" 
var val = strs[1]

New APIs on Java collections types:

strList.each(\ str -> { print(str) })

Optional

List and array expansion operator.

Not applicable

names*.length

Optional

See also