Groovy- map : every time require new instance - grails

My requirement is to get a NEW instance every time when I access the value in a MAP.
MyObject {
def type
}
def myMap = [
"key1" : new MyObject()
]
def obj1 = myMap.get("key1")
def obj2 = myMap.get("key1")
Can obj1 and obj2 be two different instances?
How will it behave if executed/accessed parallelly?

don't know what your use case is, but I guess I have the answer to your question:
def myMap = [
"key1" : new MyObject()
]
Just first instantiates a new object and then stores this object in the map. So every time you access it, you get the same object.
To create the behavior you describe, you need to add something dynamic to your map - a closure!
def myMap = [
"key2" : {-> new MyObject()}
]
but now a myMap.get("key2") still returns always the same - a closure. But if you execute it by calling myMap.get("key2")() (or short myMap.key2) you get a different object each time!
Unfortunately, this is a close as you will get. I hoped to do a trick with a key called getKey3 - I hoped that Groovy would call this "getter" when accessing key3 but this seems not to be the case.
There are other "tricks" in Groovy which could help you to achieve your goal (like MetaProgramming) but I guess there is a better solution if we would know your use case.

Related

Dart: check for updates to a property with reference types

I understand that dart uses reference types, and I'm wondering if there's a way to declare a variable as a sub-property of a property where modifying that sub-property doesn't propagate back to the original property.
I have a Foo class with a property (bars) that contains a List<Bar>. I have a method (_getBarListCurrent) that accepts an instance of Foo.
_getBarListCurrent is supposed to update the List<Bar>, and then pass both the Foo and a separate List<Bar> to a web service method to update the Foo if the list has been changed. So the web service method checks both the solo List<Bar> and the list within the foo for equality.
I tried to do this by declaring a variable within _getBarListCurrent for newBars which is equal to the List<Bar> in the Foo, then modifying bars, and then passing both the Foo and newBars to the web service.
However, any changes made to newBars also get updated in Foo.bars, so the equality check in the web service method always returns true, and that method quits without updating the web service.
Is there a way I can declare newBars and modify it so I still have an instance of Foo.bars that remains unchanged (so I can compare the old and new value before attempting to change the web service)? I've tried declaring the Foo again within the method as originalFoo but any updates to newBars also get updated in originalFoo (even if I mark it as final).
Here's how the method looks right now:
Future<Foo> _getBarListCurrent(Foo foo) async {
List<Bar>? newBars = foo.bars;
final Foo originalFoo = foo;
if (x) {
// add some items to the newBars list
}
_fooService.updateBars(foo: originalFoo, bars: newBars);
}
You have to have to different lists to be able to modify one and not the other.
You can make the copy at whichever point best matches your use-case.
The simple version is to change Foo to copy on read:
class Foo {
List<Bar>? _bars;
List<Bar>? get bars {
var bars = _bars;
return bars == null ? null : [...bars];
}
}
Alternatively, you can make the copy where you intend to modify the list:
Future<Foo> _getBarListCurrent(Foo foo) async {
var bars = foo.bars;
List<Bar>? newBars = null ? null : [...bars];
// ...

Groovy map, get, variable, Jenkins

I have a problem with mapping in Groovy.
I would like to get a value based on a variable.
def function(){
map = [
'test1': '1234',
'test2': '4567'
]
var=test1
def result = map.get.("$var")
return result
}
But, unfortunately. I always get back:
Cannot get property '[test1]' on null object
You are making a HashMap behind the scenes here and the way you are accessing it map.get.["$var"] Groovy is trying to access a key called "get" on your variable map.
You just want map[var]
Updated with BalRog's note below

How to access a "private member" of a separate instance of the same "class"?

Related question: how do implemented protected members when using the closure approach to OOP?. The problem is most likely the same, although the abstraction that I'm trying to implement is different.
I'm currently implementing a tree structure to represent a scene graph in lua. To do so, lua has several ways of abstracting the concept of classes, and I'm using this one:
new_item = function()
local _self = {}
local _parent = nil
local _children = {}
_self.add_child = function(child)
-- add child to _children
table.insert(_children, child) -- no problems here
-- set child's _parent to _self
child._parent = _self -- this doesn't work: "child._parent" doesn't even exist
end
return _self
end
a = new_item()
b = new_item()
a.add_child(b)
The object returned by new_item is a table with a single item called add_child, which is the function I defined. The local variables _self, _parent and _children are local to the scope of new_item, captured from each "method", and are effectively "private members" of the "class".
Now, to keep the tree consistent, I am creating this function add_child, which will add the passed parameter (which is expected to be another object created with new_item) to the list of children of this object, and set the child's parent to this object.
In C++, C# and Java, I have the notion of "private members", and I can access those of a different instance of the same class. In lua though, these local variables are local to the scope of new_item, so they're not part of the exported object, so I can't access them.
I would like to have a way to implement this abstraction of "accessing private members of a separate instance of the same class", or do something else, so the parent and children links are only modifiable with exported "methods" that can be proven correct.
I think that what I want to do is simply not possible in lua, short of putting _parent inside of _self (therefore making it "public"), and asking pretty please for nobody else to touch it, which is, if I'm not mistaken, how Python deals with this.
However, there might be a way of achieving this that I have not thought of, maybe using a different way to abstract the concept of "class". Does anybody know how to go about implementing the abstraction of "accessing private members of a separate instance of the same class" in lua?
function create_class()
local class = {}
-- when object is garbage-collected, its private data will be auto-removed
local private_data_of_all_objects = setmetatable({}, {__mode = "k"})
function class.create_new_object()
local object = {}
local private = {} -- private fields of this object
private.children = {}
private.parent = nil
private_data_of_all_objects[object] = private
function object.add_child(child)
table.insert(private.children, child)
private_data_of_all_objects[child].parent = object
end
return object
end
return class
end
cl = create_class()
a = cl.create_new_object()
b = cl.create_new_object()
a.add_child(b)

Using mirrors, how can I get a reference to a class's method?

Say I have an instance of a class Foo, and I want to grab a list of all of its methods that are annotated a certain way. I want to have a reference to the method itself, so I'm not looking to use reflection to invoke the method each time, just to grab a reference to it the first time.
In other words, I want to do the reflection equivalent of this:
class Foo {
a() {print("a");}
}
void main() {
var f = new Foo();
var x = f.a; // Need reflective way of doing this
x(); // prints "a"
}
I have tried using InstanceMirror#getField, but methods are not considered fields so that didn't work. Any ideas?
As far as I understand reflection in Dart, there's no way to get the actual method as you wish to. (I'll very happily delete this answer if someone comes along and shows how to do that.)
The best I can come up with to ameliorate some of what you probably don't like about using reflection to invoke the method is this:
import 'dart:mirrors';
class Foo {
a() {print("a");}
}
void main() {
var f = new Foo();
final fMirror = reflect(f);
final aSym = new Symbol('a');
final x = () => fMirror.invoke(aSym, []);
x(); // prints "a"
}
Again, I know that's not quite what you're looking for, but I believe it's as close as you can get.
Side note: getField invokes the getter and returns the result -- it's actually fine if the getter is implemented as a method. It doesn't work for you here, but for a different reason than you thought.
What you're trying to get would be described as the "closurized" version of the method. That is, you want to get the method as a function, where the receiver is implicit in the function invocation. There isn't a way to get that from the mirror. You could get a methodMirror as
reflect(foo).type.methods[const Symbol("a")]
but you can't invoke the result.

AS3: Extending The Dictionary Class - Accessing Stored Data

So I want to extend the dictionary class. Everything works so far except that in some of my methods that need to reference the dictionary's content I make a call like:
this[ key ]
It doesn't like that. It just tells me that there's no property 'key'. Is there a way to way to access the data within this class?
Also, I'm using an integer for the key.
Edit: I've found that the same behavior happens when you extend Array.
var myArray : Array = new Array();
trace( myArray[ 0 ] );
var myArrayExtender : ArrayExtender = new ArrayExtender();
trace( myArrayExtender[ 0 ] );
Where in this case, myArray returns "undefined" and myArrayExtender throws error 1069. ArrayExtender is an empty class that extends Array and calls super() in the constructor.
from what you say, i am quite sure you did not declare ArrayExtender as dynamic
in ECMAscript array access and property access are semantically equivalent ... #1069 happens, if you access an undefined property, on a sealed class, because thes do not allow adding properties at runtime ...
same thing for the Dictionary ...
greetz
back2dos

Resources