2.5 Function Type

The function type, along with the monomorph, is a type which is usually well-hidden from Haxe users, yet present everywhere. We can make it surface by using $type, a special Haxe identifier which outputs the type its expression has during compilation:

class Main {
  static public function main() {
    // (i : Int, s : String) -> Bool
    $type(test);
    $type(test(1, "foo")); // Bool
  }

  static function test(i:Int, s:String):Bool {
    return true;
  }
}

There is a strong resemblance between the declaration of function test and the output of the first $type expression, with one subtle difference: the function return type appears at the end after a -> symbol.

In either notation, it is obvious that the function test accepts one argument of type Int and one argument of type String and returns a value of type Bool. If a call to this function, such as test(1, "foo"), is made within the second $type expression, the Haxe typer checks if 1 can be assigned to Int and if "foo" can be assigned to String. The type of the call is then equal to the type of the value test returns, which is Bool.

Note that argument names are optional in the function type. If a function type has other function types as arguments or return types, parentheses can be used to group them correctly. For example, (Int, ((Int) -> Void)) -> Void represents a function which has one argument of type Int and one argument of function type Int -> Void and a return type Void.

The type of a function which takes no arguments uses () to represent the argument list:

class Main {
  static public function main() {
    // () -> Bool
    $type(test2);
  }

  static function test2():Bool {
    return true;
  }
}
Old function type notation

Before Haxe 4, the function type notation had more in common with other functional programming languages, using -> in place of commas separating the argument types. The test function above would be typed as Int -> String -> Bool in this notation. test2 would be typed as Void -> Bool.

The older notation is still supported, although newer code should use the new notation described above since it more clearly differentiates argument types from the return type.

Trivia: New function type notation

The new function type notation was based on the syntax of arrow functions, which were also introduced in Haxe 4.