Created
January 14, 2017 17:56
-
-
Save BlackHC/43eaef5f4bbd02523e567ea29858b19f to your computer and use it in GitHub Desktop.
Dynamic fields in Dart
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Copyright (c) 2016, Andreas 'blackhc' Kirsch. All rights reserved. Use of | |
// this source code is governed by a BSD-style license that can be found in the | |
// LICENSE file. | |
import 'dart:mirrors'; | |
Scope currentScope; | |
@proxy | |
class Scope { | |
final _scope = <Symbol, dynamic>{}; | |
Scope(); | |
Scope.predefined(Map<Symbol, dynamic> symbols) { | |
_scope.addAll(symbols); | |
} | |
factory Scope.clone(Scope other) => new Scope.predefined(other._scope); | |
@override | |
dynamic noSuchMethod(Invocation invocation) { | |
if (invocation.isGetter) { | |
if (_scope.containsKey(invocation.memberName)) { | |
return _scope[invocation.memberName]; | |
} else { | |
return super.noSuchMethod(invocation); | |
} | |
} else if (invocation.isSetter) { | |
final variable = MirrorSystem.getSymbol( | |
MirrorSystem.getName(invocation.memberName).split('=').first); | |
_scope[variable] = invocation.positionalArguments.first; | |
return null; | |
} else if (invocation.isMethod) { | |
return Function.apply(_scope[invocation.memberName] as Function, | |
invocation.positionalArguments, invocation.namedArguments); | |
} else { | |
throw new UnsupportedError('Neither setter, nor getter, nor method!'); | |
} | |
} | |
@override | |
String toString() => _scope.toString(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment