pigpigyyy/Yuescript

[feature request] Constructor Property Promotion

SkyyySi opened this issue · 2 comments

When writing classes, a common pattern is to do something like this:

class Something
    new: (foo, bar, biz, baz) =>
        @foo = foo
        @bar = bar
        @@biz = biz
        @@baz = baz

This can grow out-of-hand rather quickly, so my suggestion would be to allow the code above to be written like this:

class Something
    new: (@foo, @bar, @@biz, @@baz) =>

This is inspired by this feature: https://wiki.php.net/rfc/constructor_promotion

Note that this also existed in Ruby, exists in CoffeeScript, and in a more limited form in records (java, kotlin, scala).

This syntax was already taken from Moonscript's implementation, but forgot to mention it in the doc. Currently the code:

class Something
    new: (@foo, @bar, @@biz, @@baz) =>

compiles to:

local Something
do
  local _class_0
  local _base_0 = { }
  if _base_0.__index == nil then
    _base_0.__index = _base_0
  end
  _class_0 = setmetatable({
    __init = function(self, foo, bar, biz, baz)
      self.foo = foo
      self.bar = bar
      self.__class.biz = biz
      self.__class.baz = baz
    end,
    __base = _base_0,
    __name = "Something"
  }, {
    __index = _base_0,
    __call = function(cls, ...)
      local _self_0 = setmetatable({ }, _base_0)
      cls.__init(_self_0, ...)
      return _self_0
    end
  })
  _base_0.__class = _class_0
  Something = _class_0
  return _class_0
end

in Yuescript.