Exit Full View

Feather / src / dist / documentation / Classes.md

Class Definitions

class MyClass {
    ... definition of the class's methods and fields.
}

Primary Constructor

In this example, the constructor takes three parameters.

class MyClass( val foo : int, bar : String, var baz : double  ) {
    ... definition of the class's methods and fields.
}

foo is prefixed with val so foo is a final field.

baz is prefixed with var so baz is a mutable field.

bar is not a field as there is no val or var.

Secondary Constructors

Not implemented yet!

Extending a Class / Implementing Interfaces

Foo extends Bar. Bar can be a class or an interface.

class Foo : Bar {
}

As with Java, you can only extend from one class, but can implement any number of interfaces. Here we extend from class Bar, and also from the interface Runnable.

class Foo : Bar, Runnable {
    fun run() { ... }
}

Note that we can't tell which is an interface, and which is a class. To make it clearer, we explicitly could call Bar's constructor (which shows it cannot be an interface) :

class Foo : Bar(), Runnable {
    fun run() { ... }
}

Passing values to the base class's constructor :

class Hello : Greeting( "Hello" ) {
}

Fields

Use val or var inside a class to define a field.

class Foo() {
    val bar = 1
    var baz = 2
}

In bar is a final (its value cannot be changed), whereas baz is mutable. The types haven't been explicitly stated, so Feather uses the initial value to determine the type. In this case the type is int.

Explicit Types :

class Foo() {
    var bar : double = 1
}

Here bar is explicitly declared as a double. (Note the value 1 is automatically converted from an int to a double).

Use the static keyword in the same way as Java :

class Foo() {
    static var baz = "Hi"
}

Functions

Functions have two forms, an expression, or a block.

Here's an expression :

class Foo() {
    fun greeting( name : String ) = "Hello $name"
}

Note that the function's return type wasn't explicitly stated.

We could explicitly state it though :

class Foo() {
    fun greeting( name : String ) : String = "Hello $name"
}

Here's a block :

class Foo() {
    fun greeting( name : String ) : String {
        return "Hello $name"
    }
}

When using a block, you MUST include the return type explicitly, and if no type is specified, then the method does not return a value.

class Foo() {
    fun greet( name : String ) {
        println( "Hello $name" )
    }
}

Methods can be declared as static, using the static keyword :

class Foo() {
    static fun greet( name : String ) {
        println( "Hello $name" )
    }
}