Operator overloading and Java

Java doesn't support any kind of operator overloading, but it is possible to use operators with types defined in Java. We already said that Kotlin operators are functions, and if the Kotlin compiler sees a correctly named function, it will allow a matching operator to be used.

Let's go back to our Length type and define it again in Java:

public class JavaLength {

private final double value;

public JavaLength(double value) {
this.value = value;
}

public double getValue() {
return value;
}

public JavaLength plus(JavaLength other) {
return new JavaLength(this.value + other.getValue());
}
}

The Kotlin compiler sees our plus function and allows us to use the + operator to add two length objects:

val javaL1 = JavaLength(12.0)
val javaL2 = JavaLength(7.5)

val javaSum = javaL1 + javaL2
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.149.254.101