Object literals and class objects

This commit is contained in:
Andrey Breslav
2010-11-19 16:01:26 +03:00
parent 1af0027ee7
commit 350b4ba1a4
3 changed files with 46 additions and 18 deletions
+17 -9
View File
@@ -1,17 +1,16 @@
class Foo(bar : Bar) {
class object {
private val cache = HashMap<Bar, Foo>()
} static {
private val cache = HashMap<Bar, Foo>()
// 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<K, V>.cachedLookup(key : K, lazy value : V) : V {
var v = this[key]
if (v == null) {
v = value
this[key] = value
}
return v
}
+7 -3
View File
@@ -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
+22 -6
View File
@@ -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
;
objectLiteral
: "object" delegationSpecifier{","} classBody?
;
/* Factory methods:
objectLiteral
: "object" delegationSpecifier{","} ("{" objectLiteralMember{","} "}")?
;
objectLiteralMember
: memberDeclaration
: factoryMethod
;
factoryMethod
: accessModifier? SimpleName typeParameters? functionParameters functionBody
;
*/