Object literals and class objects
This commit is contained in:
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
;
|
||||
|
||||
*/
|
||||
Reference in New Issue
Block a user