Warm tip: This article is reproduced from stackoverflow.com, please click
dart java

What is the equivalent of the following statement in java?

发布于 2020-03-27 15:40:41

I'm writing a javafx application and I would like to call functions and set variables in the same statement where I declare an instance of a class.

I can do this in dart like the following code, but can I do this in java?

class MyClass{
  int someVar =1;
  someFun(){
     print("something");
  }
}

void main(){
 MyClass newClass = new MyClass()
  ..someVar = 2 // how can I do this in java?
  ..someFun();

 print(newClass.someVar);

}
Questioner
Ammar
Viewed
43
Tidder 2020-01-31 16:17

Actually you can't do this in Java - at least not in the Dart style. The double dot (..) notation is a Dart language feature, which Java simply does not have. However, for this simple example, you can achive the same result like this:

class MyClass {
    int someVar = 1;

    MyClass setSomeVar(int i) {
        someVar = i;
        return this;
    }

    MyClass someFun() {
        System.out.println("something");
        return this;
    }
}

public static void main(String[] args) {
    MyClass newClass = new MyClass()
            .setSomeVar(2)
            .someFun();

    System.out.println(newClass.someVar);
}

As in Dart, this only works for methods that (normally) do not have a return value (e.g. void methods).