Classes and Constructors
In Klyn, a class is both a runtime type and the main unit of object-oriented design. This page
covers class declarations, constructors, instance and static members, file layout rules, and
the basics of working with this.
public class Point:
public property x as Int = 0
public property y as Int = 0
public Point(x as Int = 0, y as Int = 0):
this.x = x
this.y = y
public override toString() as String:
return f"[{this.x}, {this.y}]"
Constructors are named after the class. There is no separate constructor or
new keyword.
p1 = Point()
p2 = Point(10, 20)
p3 = Point(
1,
2
)
Constructor calls use ordinary call syntax and may span multiple lines when readability benefits.
this
Use this when you want to emphasize that a property or method belongs to the
current instance.
public class Counter:
public property current as Int = 0
public tick() as Void:
this.current++
public reset() as Void:
this.current = 0
public class Settings:
public static defaultName = "Klyn"
print(Settings.defaultName)
Static members belong to the type, not to a specific instance.
Every object inherits deepCopy() as this. The special return type
this means that the static result type follows the static receiver type. At runtime,
the copied object keeps its concrete subtype, and nested mutable objects and collections are
copied recursively. Cycles and shared references are preserved.
shape as Shape = Circle(10.0)
copy = shape.deepCopy() # statically Shape, dynamically Circle
assert copy is Shape
assert copy is Circle
assert copy is not shape
Because the static receiver above is Shape, the result cannot be assigned directly
to Circle without an explicit checked cast, even though its runtime type is a circle.
- A public class must live in a file with the same name.
- If the file declares a package, the folder path must match that package.
- Only one public class should occupy that file.
package my.app.core
public class User:
pass
The example above belongs in my/app/core/User.kn.
Inside a class body, methods are declared directly with modifiers such as
public, private, or static. They do not use the
def keyword.