charly icon indicating copy to clipboard operation
charly copied to clipboard

Enums

Open KCreate opened this issue 9 years ago • 3 comments

enum MyEnum {
  Foo
  Bar
  Baz
}

MyEnum.Foo # => 0
MyEnum.Bar # => 1
MyEnum.Baz # => 2

Enums can also have static methods

enum MyEnum {
  Foo
  Bar
  Baz

  func is_foo(value) {
    value == @Foo
  }
}

The values of an enum are Numeric values starting at 0, incrementing with each value added to the enum. The enum is represented as an object.

The above code is equivalent to the following object literal:

let MyEnum = {
  const Foo = 0
  const Bar = 1
  const Baz = 2

  func is_foo(value) {
    value == @Foo
  }
}

KCreate avatar Dec 18 '16 19:12 KCreate

@KCreate Good idea, that gives us more opportunities to seperate the functions from other objects

ghost avatar Apr 22 '17 07:04 ghost

@KCreate But are the functions actually necessary? Any examples for a good use?

daniel-Q6wUOI avatar Dec 12 '17 20:12 daniel-Q6wUOI

Writing code with enums usually requires comparing them every so often. Sometimes that code becomes long and complicated. Allowing functions directly inside enums makes it possible to encapsulate logic and abstract implementation details away.

En example that comes to mind is checking whether a type of token is a keyword or not.

enum Token {
  Let
  Const
  If
  Integer

  func is_keyword() {
    return self == Token.Let || self == Token.Const
  }
}

KCreate avatar Dec 12 '17 20:12 KCreate