diff --git a/examples/src/Factories.jetl b/examples/src/Factories.jetl index 27102c68250..fa8d464897e 100644 --- a/examples/src/Factories.jetl +++ b/examples/src/Factories.jetl @@ -1,17 +1,16 @@ class Foo(bar : Bar) { + class object { + private val cache = HashMap() -} static { - private val cache = HashMap() +// Factory method: + Foo() = Foo(null); - Foo() { - return Foo(null); +// Factory method: + Foo(bar : Bar) = cache.cachedLookup(bar, this(bar)) } - Foo(bar : Bar) { - if (bar in cache.keys) return cache[bar] - val newFoo = this(bar) // calls the primary constructor - cahce[bar] = newFoo - return newFoo + fun doFoo() { + // ... } } @@ -23,4 +22,13 @@ val foo = Foo(Bar()) // Subclass (Foo must be marked as extendable/open, i.e. ont sealed) class FooSub(S : String) : Foo() { // Delegates to Foo created as a result of the factory method Foo() +} + +extension Map.cachedLookup(key : K, lazy value : V) : V { + var v = this[key] + if (v == null) { + v = value + this[key] = value + } + return v } \ No newline at end of file diff --git a/grammar/src/class_members.grm b/grammar/src/class_members.grm index d78cdfdc423..127c85a2d87 100644 --- a/grammar/src/class_members.grm +++ b/grammar/src/class_members.grm @@ -30,11 +30,15 @@ class Example(a : Foo, i : Int) : Bar(i), Some { // h5. Grammar memberDeclaration + : classObject : constructor : method : property - : class //TODO : static -// : constant ??? + : class + ; + +classObject + : "class" objectLiteral ; constructor @@ -51,7 +55,7 @@ super ; method - : methodModifier* "fun" SimpleName functionParameters (":" type)? functionBody? + : methodModifier* "fun" SimpleName typeParameters? functionParameters (":" type)? functionBody? ; functionParameters diff --git a/grammar/src/expressions.grm b/grammar/src/expressions.grm index 38cda83ca3e..ae0c0ac7814 100644 --- a/grammar/src/expressions.grm +++ b/grammar/src/expressions.grm @@ -11,9 +11,8 @@ expression : expressionWithPrecedences : match : if - : "new" constructorInvocation - : anonymousInnerClassInstantiation // TODO -// TODO: list comprehension + : "new" constructorInvocation // TODO: Do we need "new"?, see factory methods + : objectLiteral : jump ; @@ -159,6 +158,23 @@ arrayAccess : "[" expression "]" ; -anonymousInnerClassInstantiation - : "object" delegationSpecifier{","} classBody - ; \ No newline at end of file +objectLiteral + : "object" delegationSpecifier{","} classBody? + ; + +/* Factory methods: + +objectLiteral + : "object" delegationSpecifier{","} ("{" objectLiteralMember{","} "}")? + ; + +objectLiteralMember + : memberDeclaration + : factoryMethod + ; + +factoryMethod + : accessModifier? SimpleName typeParameters? functionParameters functionBody + ; + +*/ \ No newline at end of file