What is the Java equivalent of Swift extensions?

According to the official Swift doc ( Swift extension doc ), Swift extensions look like Java enums.

Swift extensions:

extension Double {
var km: Double { return self * 1_000.0 }
var m: Double { return self }
var cm: Double { return self / 100.0 }
var mm: Double { return self / 1_000.0 }
var ft: Double { return self / 3.28084 }
}

let oneInch = 25.4.mm
print("One inch is \(oneInch) meters")
// prints "One inch is 0.0254 meters"

      

I tried to represent this in Java and came up with the following code. Is this Java representation correct? or is there any other way of representing this?

public enum LengthMetric {

km(1.0e3), mm(1.0e-3), m(1.0e0);

private final double number;

LengthMetric(double number) {
    this.number = number;
}

double getValue(double value) {
    return value * number;
}

public static void main(String[] args) {


    double originalValueInMeters = 3.0;

    System.out.printf("Your value on %s is %f%n", km,
            km.getValue(originalValueInMeters));

    double oneInch = mm.getValue(25.4);
    System.out.printf("One inch on %s is %f%n", m,
            oneInch);

}
}
Your value on km is 3000.000000
One inch on m is 0.025400

      

+3


source to share


1 answer


Swift extensions have nothing to do with enumerations. They provide a way to extend a class for which you may not even have the source code. For example:

extension Double {
    func multiplyBy2() {
         return self * 2
    }
}

      

This will make the multiplyBy2 function available through your application for any Double instance, so you can simply do something like:

let myDouble: Double = 2.0
NSLog( "myDouble * 2: \(myDouble.multiplyBy2())" );

      

You can have as many extensions above the class as possible. Extensions allow you to add methods and computed properties, but they are not saved. But it can be achieved with the Objective-C runtime.

Java does not support this behavior.



However, Groovy (a dynamic Java-based language that runs on the JVM) has long supported this behavior. With Groovy, you can extend classes dynamically by adding closures as properties to the metaClass (much like the way you add methods to a JavaScript object).

For example:

Double.metaClass.multiplyBy2 = { return delegate * 2 }

      

This will be equivalent to the previous Swift extension.

You can use it like this:

Double myDouble = 2.0
println "myDouble * 2: ${myDouble.multiplyBy2()}"

      

+8


source







All Articles