-
Notifications
You must be signed in to change notification settings - Fork 3
oop_proposal
Matěj Štágl edited this page May 19, 2022
·
7 revisions
Defining a class:
class Dog {
var name
Dog = (name) => {
this.name = name
}
bark = () => {
return `woof {this.name}`
}
}
Constructors:
myDog = new Dog("rex")
myDog.bark() // woof rex
In case constructor is not defined, it is not called.
class C {
}
c = new C("arg1") // arguments can be passed regardless of a constructor presence. If no constructor is found, they are ignored silently.
Annotations can be attached to classes.
@MyAnnotation
class Animal {
}
Only single level inheritance is supported.
class Animal {
var name
bark = () => {
print(this.name)
}
Animal = (name) => {
this.name = name
}
}
class Dog : Animal {
}
dog = new Dog("rex") // here Dog has no constructor declared. We look for one in parent class, if present.
dog.bark() // rex
We can call parent (base) class members.
class Animal {
var name
Animal = () => {
name = "default animal"
}
}
class Dog : Animal {
Dog = () => {
base() // calls Animal's constructor, arguments can be passed as usual
}
}
This works for non-constructor methods as well. Unlike in constructor, method to be called needs to be specified explicitly as base.Method()
.
class C {
function X() {
return "c"
}
}
class CPP : C {
function X() {
return `base.X()++`
}
}
c = new C().X() // returns "c++"
Mixins can be used to inject functionality into classes.
class Animal {
bark = () => {
return "I am an animal"
}
}
mixin IMeow {
meow = () => {
return "meow"
}
}
mixin IBark {
canWoof = true
woof = () => {
return "woof"
}
bark = () => {
return "I am a dog"
}
}
class CatDog : Animal with IMeow, IBark {
bark = () => {
return "I am a CatDog"
}
CatDog = () => {
print(bark()) // prints "I am CatDog". While IBark provides an implementation of this method, it is overriden by a local implementation.
print(super.bark()) // prints "I am an animal" as provided by Animal parent class
print(woof()) // prints "woof" as provided by mixin IBark
print(meow()) // prints "meow" as provided by mixin IMeow
print(canWoof) // prints "true" as provided by mixin IBark
}
}
catDog = new CatDog()
Annotations can be attached to mixins. These annotations are then passed on to classes using said mixins.
@MyAnnotation("param1")
mixin IMixin {
}
@MyAnnotation("param1", "param2")
class C with IMixin { // there are two annotations attached to class C "@MyAnnotation("param1", "param2") and @MyAnnotation("param1")
}
Annotations are ordered as class annotations > base annotations > mixin annotations
to correspond with the syntax class Class : Base with Mixin
.