3

In switching from AS3 to JAVA I am finding there are a few minor niceties that I miss, one of them specifically being the with keyword. Is there anything similar to this in JAVA (6 or less)?

I am parsing values out of an object and would rather write something like:

/** Example in AS3 **/
function FancyParsingContructorInAS3(values:Object):void { 
    with (values) { 
        this.x = x; // functionally equivalent to `this.x = values.x;`
        this.y = y; 
        this.width = width; 
        this.height = height; 
    } 
}
Blake Barrett
  • 206
  • 1
  • 10

1 Answers1

2

There seem to two use cases for the with statement.

1) To change the value of this in a particular context

public class App {

     public void stuff() {
         //this refers to the current instance of App
         final Object obj = new Object();
         with(obj) {
         //this refers to obj
         }
     }
}

There is nothing like this in Java. You would just put the method code into the Object.

2) To import methods from another class so that they can be used unqualified.

public static void main(String[] args) throws Exception {
    System.out.println(Math.max(Math.PI, 3));
}

Can be changed, in java with import static. This allows static members of another class to be imported into the current class. Adding the following three import statements:

import static java.lang.System.out;
import static java.lang.Math.max;
import static java.lang.Math.PI;

Would allow you to instead write

public static void main(String[] args) throws Exception {
    out.println(max(PI, 3));
}

You can see that is makes the code somewhat less readable however. It's not especially obvious where out, max and PI come from.

Boris the Spider
  • 59,842
  • 6
  • 106
  • 166
  • Wow, that's terrible, but fascinating! – Blake Barrett Aug 06 '13 at 23:04
  • Looks like `Kotlin` implemented this functionality to match how `Action Script` did. https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/with.html – Blake Barrett Nov 24 '20 at 00:39
  • @Blake it’s more than Kotlin added extension functions - which allowed them to implement `with`. I don’t know how it works in ActionScript but in Kotlin `with` simply a utility method that executes a lambda as an extension function to the passed in object. In fact it’s one of 6 “scope functions” in Kotlin. – Boris the Spider Nov 24 '20 at 19:41