Classes

syntax

[abstract] class varname["<" type ">"][@ version] [extends varname] {
(
[private | protected | public] (field | method)
|
(private | protected | public) {
(field | method)+
}
)*
}

field = varname[: type] [= value]

method = [abstract] [async] varname([[parameter1] [, [parameter2] ... [, [parameterN]]])[: type] [~ class1 [, class2 ... [, classN]]] [ => expression | {
...statements
}]

example

class Shape {
private {
_color: String
}
draw(): String {
return `I'm drawing with a \(this._color) pen.`
}
}

this aliasing

@x is an alias for this.x, this._x or even this.x().

class Shape {
private {
_color: String
}
draw(): String {
return `I'm drawing with a \(@color) pen.`
}
}

constructor

The constructor is called when creating a new object like new Shape()

class Shape {
private _color: String
constructor(@color)
// automatically set the instance variable '_color' as the parameter 'color'
}

destructor

The destructor is called by the statement delete.

extern console
class Shape {
private {
_color: String
}
constructor(@color)
destructor() {
@color = null
}
}
let s = new Shape('red')
delete s
// the destructor is called and the variable `s` is unreferenced

class members

Class members are declared with the modifier static.

class Rectangle {
public static shape() => 'Rectangle'
static {
color() {
return '1.0.0'
}
}
}
console.log(Rectangle.shape(), Rectangle.color())

superclass & subclass

extern console
class Shape {
private {
_color: String
}
constructor(@color)
// automatically set the instance variable '_color' as the parameter 'color'
destructor() {
@color = null
}
color() => @color
color(@color) => this
draw(): String {
return `I'm drawing with a \(@color) pen.`
}
}
class Rectangle extends Shape {
draw() {
return `\(super()) I'm drawing a \(@color) rectangle.`
}
}
let r = new Rectangle('black')
console.log(r.draw())
// I'm drawing with a black pen. I'm drawing a black rectangle.

abstract

abstract class AbstractGreetings {
private {
_message: String: ''
}
constructor() {
this('Hello!')
}
constructor(@message)
abstract greet(name): String
}
class Greetings extends AbstractGreetings {
greet(name) => `\(@message)\nIt's nice to meet you, \(name).`
}

versioning

kaoscript classes can be signed with a version which could be used for serialization.

class Rectangle@1.0.0 {
private {
_color: String
}
constructor(@color = 'black')
draw(canvas) {
return `I'm drawing a \(@color) rectangle.`
}
}
console.log(Rectangle.name)
// Rectangle
console.log(Rectangle.version)
// 1.0.0