Simplest way to implement one-method interfaces in Groovy? - groovy

What is the simplest way to implement one-method interfaces in Groovy?
Ones, like Runnable or FileFilter?
For example, to list files I wrote java-like:
// works Java-like
new File(".").listFiles(new FileFilter() {
#Override
boolean accept(File file) {
!file.isDirectory()
}
}).each { println it.absolutePath }
but closure-like does not work
// does not work
new File(".").listFiles({file -> !file.isDirectory()}).each { println it.absolutePath }
Is it possible to implement it using closures or something?

In this particular example the following piece of code should work:
return [downloadFolder: downloadFolder.listFiles({ file ->
return !file.isDirectory()
})]
Basically interfaces can be implemented using a Map.
EDIT
In this particular example it should be:
new File(".").listFiles({file -> !file.isDirectory()} as FileFilter).each { println it.absolutePath }

Related

Is possible in groovy to remove a object from list through the object?

Is possible in groovy to remove a object from list through the object?
I know how to remove from the list, but can I remove it from the list with only know the reference of the certain object. (I don't want a null object in the list)
Probably it is not possible, but Groovy have surprises.
class Foo() {
List<Boo> boos
}
class BoosHandler {
void doSomethingWithBoo() {
boos.each {
analyse(it)
}
}
void analyse(Boo boo) {
if(boo.something == "wrong") {
remove(boo) // Pseudo style for removing object boo from the list (Foo.boos)
}
}
}
No, not possible.
I would also not do this, as in a multi-threaded environment it would be unpredictable...
You're better (as you probably know) doing:
List<Boo> filter(String notThis) {
boos.findAll { it.something != notThis }
}
ie: return a new list, and don't change the original

How to make a local extension method avaiable in a function with receiver?

I found an interesting thing, but I couldn't do it. Is there any way to make the local extension method available in a function with receiver.
val list = ArrayList<Any>();
fun <T> Array<T>.bind(context: MutableList<in T>, block: Array<T>.() -> Unit) {
fun Array<T>.save() {
context.addAll(this);
}
block();
}
arrayOf(1, 2, 3).bind(list) {
save(); //todo: how to bind extension in execution scope
};
I know there is an alternative way by introducing another type for the receiver, but I want to avoid it. for example:
interface Savable {
fun save();
}
fun <T> Array<T>.bind(context: MutableList<in T>, block: Savable.() -> Unit) {
val proxy = object : Savable {
override fun save() {
context += this#bind;
}
};
proxy.block();
}
There is no such feature yet, and I think in near future it won't be added either. You should just use your second version. Don't care about adding an wrapper class. The idea of avoiding introducing a wrapper class is actually, as long as you are using JVM backend, just nonsense, because by using local function you are actually adding a local class.
This is the equivalent Java code of your kotlin function, after fixing as you have suggested, with the assumption that your bind function lives in file bind.kt:
public final class BindKt {
public static <T> void bind(T[] receiver, List<? super T> context, Function1<T> block) {
class Local { // the name of local class is unimportant, as it's generated by compiler. It should looks like "package.name.BindKt$bind$X" where X is a number.
public void save(T[] receiver) {
context.addAll(receiver);
}
}
block.invoke(this); // this won't compile. Neither will yours.
}
}
As you can see save is NOT compiled to a static method, which means, if your block somehow ever called that save, an instance of Local must be fist created. So, no matter what you do, as long as you used a local function, there is basically no point in avoiding introduing a wrapper class. Your second solution is good, and just use it. It's both elegant and efficient enough.
If you really don't want add a class/object creation, move these extension functions to a package scope, and let clients import them.

Using abstracts as HashMap keys in Haxe

I'm trying to create a haxe.ds.HashMap where the keys are an object I don't control. Thus, they don't implement the hashCode method and I can't change them to.
I would really like to use an abstract to accomplish this, but I'm getting some compile time errors.
Here is the code I'm playing with:
import haxe.ds.HashMap;
abstract IntArrayKey( Array<Int> ) from Array<Int> {
inline public function new( i: Array<Int> ) {
this = i;
}
public function hashCode(): Int {
// General warning: Don't copy the following line. Seriously don't.
return this.length;
}
}
class Test {
static function main() {
var hash = new HashMap<IntArrayKey, Bool>();
}
}
The compile errors are:
Test.hx:15: characters 19-51 : Constraint check failure for haxe.ds.HashMap.K
Test.hx:15: characters 19-51 : IntArrayKey should be { hashCode : Void -> Int }
But the moment I change my abstract over to a class, it compiles fine:
import haxe.ds.HashMap;
class IntArrayKey {
private var _i: Array<Int>;
inline public function new( i: Array<Int> ) {
this._i = i;
}
public function hashCode(): Int {
// General warning: Don't copy the following line. Seriously don't.
return this._i.length;
}
}
class Test {
static function main() {
var hash = new HashMap<IntArrayKey, Bool>();
}
}
It's the exact same hashCode implementation, just a different context. Is there some way to accomplish this? Or is it a language limitation?
As far as I know, abstracts currently can't satisfy type requirements like this, quoting from the code:
abstract HashMap<K:{ function hashCode():Int; }, V >(HashMapData<K,V>) {
So, I doubt you could do that in a meaningful way.
Important point would be that while abstracts can sometimes provide overhead-free abstractions which is quite useful for optimizations, the time needed to instantiate(probably hidden from sight with abstract Name(Holder) to Holder having #:from Array<Int> and #:to Array<Int>) holder for your array which will have the required method isn't that high(compared to usual runtime overheads), and unless it is a really frequent code, should be your first way to go.
However, the HashMap code itself is quite short and simple: here.
You could just copy it and make it work with your example. Maybe you could even forge a better yet generic version by using interfaces(though I'm not sure if abstracts can actually implement them).

Passing parammeters

Hi guys I have one question,
If I have a sequence of methods for example:
Main()
{
Method1();
}
Method1()
{
Method2();
}
Method2()
{
Method3();
}
Method3()
{
ObtainsUserPermission(httpContext.Current.User.Name);
}
How is the best way to do it, using the parammeter "httpContext.Current.User.Name" in the last Method3, or passing by parammeter in each method? Like this:
Main()
{
Method1(httpContext.Current.User.Name);
}
Method1(string name)
{
Method2(name);
}
Method2(string name)
{
Method3(name);
}
Method3(string name)
{
ObtainsUserPermission(name);
}
thank you for all.
This smells like magic parameters.
A good rule of thumb is - if you wish your execution of method3() to depend on the name, pass the name as a parameter. In general, you shouldn't use globals inside functions. It can become complicated to debug and maintain. An exception is members of a class, in which case your members are visible inside the methods and there is no need to pass them as parameters.

Groovy Prototype Object

I have a method with an incoming variable, which represents a script.
e.g.
hello.groovy
Foo.init(this)
Foo.groovy
class Foo {
static init(app) {
}
}
What is the best way to add a ton of new functionality to the app variable in the init method? Basically, I would like to add all the functionality of another object to the app object.
For instance, if I had another class:
class Bar {
def a() { }
def b() {
}
}
I would like the app object to basically be a new Bar(). In JavaScript, this is easy by using the prototype object, but I cannot seem to get it working in groovy. What is the best way to accomplish this? Or should I be doing something differently?
YourClass.metaClass.static.yourMethod is the most similar to JS prototype I've seen in Groovy. Check this link out:
Groovy meta-programming - adding static methods to Object.metaClass
Cheers.
There are several ways to do this and each has advantages and disadvantages. On the Groovy Documentation page, the section on Dynamic Groovy illustrates several of these. If I understand you correctly, the simplest way is to just use the metaClass of an instance to add new functionality, a la:
class Foo {
static void init (a) {
a.metaClass.a = { println "a()"; }
a.metaClass.b = { println "b()"; }
}
}
def myObject = new Object();
Foo.init (myObject);
myObject.a();
myObject.b();
The easiest way to do this would be with a mixin. Basically you can call mixin on app's class and pass it another class to incorporate that functionality into it.
I've modified your example to show this mixing in the Bar class.
class Foo {
static init(app) {
app.class.mixin Bar
}
}
class Bar {
def a() { println "a called" }
def b() {
println "b called"
}
}
def app = new Object()
Foo.init(app)
app.a()
app.b()
The output of this would be:
a called
b called
In this case I added Bar to the Object class but you could add it to any class in your application.

Resources