HaxeFoundation / haxe

Haxe - The Cross-Platform Toolkit
https://haxe.org
6.18k stars 655 forks source link

ReadOnlyArray - cool! But what about ReadOnlyMap? #8913

Open CrazyFlasher opened 5 years ago

RealyUniqueName commented 5 years ago

I'm not sure if it's even possible to make an abstract on top of our @:multiType implementation...

Simn commented 5 years ago

Please don't try that...

Gama11 commented 5 years ago

I think a ReadOnlyMap makes a lot of sense though.

RealyUniqueName commented 5 years ago

First we need a better Map implementation than @:multiType.

nadako commented 5 years ago

I mean we could copy-paste the Map abstract and remove the set/remove/clear methods.

romamik commented 4 years ago

There is no problem with abstracts over Map, except for creating new Map instances. But there is no need for that for ReadOnlyMap.

package;

@:forward(exists, keys, iterator, keyValueIterator)
abstract ReadOnlyMap<K, V>(Map<K,V>) from Map<K,V> {

    @:arrayAccess
    public inline function get(key: K): Null<V> {
        return this.get(key);
    }
}

class Main {

    static function main() {

        var map: ReadOnlyMap<Int, Int> = [100 => 200, 300 => 400];
        trace(map[100]);
        trace(map.exists(100));
        for (k => v in map) {
            trace('$k=>$v');
        }
        for (v in map) {
            trace(v);
        }
    }   
}