Creating Objects

In Flix, we can create objects using syntax similar to Java.

For example:

import java.io.File

def main(): Unit \ IO = 
    let f = new File("foo.txt");
    println("Hello World!")

Here we import the java.io.File class and instantiate a File object by calling one of its constructors using the new keyword.

The File class has multiple constructors, so we can also write:

import java.io.File

def main(): Unit \ IO = 
    let f1 = new File("foo.txt");
    let f2 = new File("bar", "foo.txt");
    println("Hello World!")

Flix resolves the constructor based on the number of arguments and their types.

As another example, we can write:

import java.io.File
import java.net.URI

def main(): Unit \ IO = 
    let f1 = new File("foo.txt");
    let f2 = new File("bar", "foo.txt");
    let f3 = new File(new URI("file://foo.txt"));
    println("Hello World!")

We can use a renaming import to resolve a clash between a Java name and a Flix module:

import java.lang.{String => JString}

def main(): Unit \ IO = 
    let s = new JString("Hello World");
    println("Hello World!")

Here JString refers to the Java class java.lang.String whereas String refers to the Flix module. Note that internally Flix and Java strings are the same.

Note: Any interaction with Java code always has the IO effect.

Note: In Flix, Java classes must be imported before they can be used. In particular, we cannot write new java.io.File(...).