Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the Java equivalent to Swift "extensions"?

According to the official Swift doc (Swift extension doc), the Swift extensions looks 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 are 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
like image 457
kalan nawarathne Avatar asked Dec 20 '22 02:12

kalan nawarathne


1 Answers

Swift extensions have nothing to do with enums. They provide a way of extending a class for which you might not even have the source code. For example:

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

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

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

You can have as many extensions over a class as you wish. Extensions allow you to add methods and calculated properties, but not stored properties. But that can be achieved by using the Objective-C runtime.

Java does not support this kind of behavior.

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

For example:

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

That would be equivalent to the previous Swift extension.

You could use it then this way:

Double myDouble = 2.0
println "myDouble * 2: ${myDouble.multiplyBy2()}"
like image 184
ncerezo Avatar answered Jan 01 '23 18:01

ncerezo