Skip to content

static_classes_proposal

Matěj Štágl edited this page Sep 25, 2022 · 2 revisions

Static classes proposal

Extends OOP proposal.

Static classes and static members offer a mechanism to use class as a container that has no internal state. This makes it a convenient choice for implementing a set of pure functions.

Static fields

class Math {
  static PI = 3.1415926535

  static function Sum(a, b) {
    return a + b
  }

  static CircleArea = (r) => {
   return this.PI * r ** 2
  } 
}

print(Math.Sum(5, 1))
print(Math.CircleArea(10))
print(Math.Sum(5, 1))
print(Math.CircleArea(10))

Static classes

Following constraints are placed on a static class:

  • all members must be static
  • can't be instantiated
  • can't be used as a base class
  • can't contain a constructor
static class Math {

  Math() { // <-- throws an error, cannot 

  }

  function foo() { // <-- throws an error, all members of a static class must be static

  }
}

new Math() // <-- throws an error, static class can't be instantiated

class Math2 : Math { // <-- throws an error, static class is sealed

}