wren-lang / wren

The Wren Programming Language. Wren is a small, fast, class-based concurrent scripting language.
http://wren.io
MIT License
6.86k stars 550 forks source link

[Feature] Default constructor #1038

Open MatheusRich opened 3 years ago

MatheusRich commented 3 years ago

Hi everyone! First I'd like to thank y'all for this language!

I was playing with Wren in the browser and noticed that Classes requires a constructor, even if it does nothing. Here's what I was creating:

class A {
  construct new() {}  // This does "nothing", but it's required

  test() {
    System.print("Called with 0 args")
  }

  test(a) {
    System.print("Called with 1 arg: '%(a)'")
  }
}

var o = A.new()
o.test()
o.test("yay")

That seemed unnecessary verbosiness for a scripting language IMHO. On the other hand, I see that this can be intentional, since "a class with no state should be just a module".

So I opened this just to clarify if it is a language design choice.

ChayimFriedman2 commented 3 years ago

How would the default constructor be named?

CrazyInfin8 commented 3 years ago

I think if it's a class with no fields, wouldn't it be better to use static methods instead?

class A {
  static test() {
    System.print("Called with 0 args")
  }

  static test(a) {
    System.print("Called with 1 arg: '%(a)'")
  }
}

A.test()
A.test("yay")

// can also assign variable `o` to the class itself as well
var o = A
o.test()
o.test("yay") 
MatheusRich commented 3 years ago

@CrazyInfin8 Yeah, that's what I thought. I was just playing with classes and started creating dumb methods. I was expecting it to "just work" since it would in Ruby (my main language). Anyway, I didn't know if it was worth adding this feature, so I asked here.

ChayimFriedman2 commented 3 years ago

There is a crucial difference between Ruby and Wren in this aspect: Ruby defines only one constructor, with the reserved word new. In Wren, constructors are just methods (special kind of them), and there can be multiple of them, possibly with different names.

MatheusRich commented 3 years ago

@ChayimFriedman2 oh, I didn't know that. I was just expecting construct new() {} to already be there. Feel free to close this, if it's not useful!