Eclipse Xtend: Overriding equals() vs. operator_equals() - operator-overloading

Which method should I implement in Xtend if I want to declare equality check?
AFAIK if I use '==' operator, then it gets compiled as equals() call in Java.
If so, then why would I define an operator_equals() when I can simply override equals()?
UPDATE: As #kapex pointed out it is not recommended to override '==' as it can lead to code behaving differently in Xtend and Java, sample below:
class Person {
override equals(Object person) {
true // We are all the same
}
def operator_equals(Person person) {
false // We are all different
}
}

If your goal is to change "equal to" behavior, then you should simply override equals (and hashCode).
You would only define operator_equals if you want it to have different behavior than equals. But you generally wouldn't want that.
If you overload the == operator, the original equals method still exist and some some code might use the operator while other code will use equals (for example Java libraries). This sounds like a good way to break something.
It makes sense for Xtend to provide the ability to overload all operators for some odd use cases or even just for consistency, but in my opinion redefining existing operator behavior is bad practice and should be avoided. It's much safer to only overload operators that are not yet defined for a type.

Related

Boolean extension function

When I try to create Extension Function to set Boolean true or false like the below.
Boolean.setTrue(){
this = true
}
Boolean.setFalse(){
this = false
}
It says variable expected. How to achieve this.
You cannot change the value of this, this would break a lot of assumptions, even if you could you would not be able to change the value, as Booleans are immutable.
More generally, there is a fine line between simplifying code, and making it more complex, and in this case that would complicate it. I would agree that adding String.splitByDot() may make sense, but replacing idiomatic code tends to just make the code more complex, as you start to wonder why the code had to be replaced.
Sorry but this does not make sense. Just use myBool=false, it's what anyone understands and cannot get any more readable.
Also Boolean is immutable and what you're trying isn't possible anyways.
We have to be careful not to overuse extensions. It's one of the greatest features Kotlin (and others) offers, but in certain examples, e.g. trying to change the way a dead simple Boolean is being assigned, it's getting dangerous IMHO (luckily it's not possible).
Here is an extension method that works in C# 7.2 or later:
public static class Extensions
{
public static bool Toggle(ref this bool b) => b = !b;
}
Then elsewhere, something like this will work:
bool b1 = true; // Works for primitive bool type.
Boolean b2 = true; // Works for Boolean object, too.
b1.Toggle();
b2.Toggle();
The only benefit I see to using an extension method is to shorten lines with long bool expressions, such as replacing:
this.SomeObjectWithALongName.SomeVerboselyNamedProperty
= !this.SomeObjectWithALongName.SomeVerboselyNamedProperty
with
this.SomeObjectWithALongName.SomeVerboselyNamedProperty.Toggle();
I don't know what drawbacks this extension method may have.
The reason you can't do this is that you cannot reassign the receiver in an extension function.
It's not possible to change the value of the Boolean because it is immutable.
The reason you can do this comes to a lack of implementation of Kotlin extension probably due to the fact Extension in Kotlin are resolved Statically (even probably really static).
So 'this' in a static context doesn't make sense.

Use mocked function return value in real function call

Is it possible to use a mocked function inside a real function call? Both functions are in the same object. So for example, if I have
obj A {
def mockThis(value: Int): Int = {
value*5
}
def realFuncIWantToTest(value: Int): Int = {
val v = mockThis(value)
v
}
}
Obviously this is an extremely simple case and this isn't what my code is doing (v is actually a complicated object). Essentially I want realFuncIWantToTest to use the mocked function return value that I define.
Thanks!
You might be able to do this using Mockito's spies; see here for an example on that.
Spies basically work by having that spy wrapping around a real object of your class under test.
But one word here: even when it is possible, please consider changing your design instead. This "partial mocking" is often a good indication that your class is violating the single responsibility principle. Meaning: a class should be responsible for "one" thing. But the idea that you can / have to partially mock things within your class indicates that your class is responsible for at least two, somehow disconnect aspects.
In that sense: the better approach would be that mockThis() would be a call on another object; which could be inserted via dependency injection into this class.
Long story short: at least on a Java level your idea should work fine (where I have certain doubts that Mockito will work nicely with your scala objects) from a technical perspective; but from a conceptual point point; you should rather avoid doing it this way.

What kind of impact does applying all these Scala traits have at runtime?

Imagine this:
val myObject = if(someCondition) {
new Whatever with Trait1
} else if(otherCondition) {
new Whatever with Trait2 with Trait3 with Trait4
} else {
new Whatever with Trait5
}
Is the myObject object "composed" at runtime, or is the scala compiler smart enough to generate the appropriate code at compile time? What kind of performance impact will it have on the code if you have multiple places that are applying traits like in the above code?
It's composed at compile-time
The traits will be added as interfaces to the resulting type, and any concrete methods from those traits will (usually) be copied to the class in their entirety.
Occasionally, the compiler may have to provide concrete implementations via forwarders to static methods, but this isn't usually the case.
Scala will create three anonymous classes, (except the last condition is a syntax error).
Note: These classes will be named using the order in which they are defined in the scope they are defined. So... OuterClass$anon$1 -> 3. Please avoid using these anonymous classes in any long-term Java-serialization as this locks down the order of anonymous classes in your code.
Other than that, it's an awesome convenience feature!

Using the override keyword on implementations of abstract methods

Is it good practice to use the override keyword when implementing abstract methods defined in traits?
trait Tooth {
def ache(): Unit
}
class Molar extends Tooth {
override def ache(): Unit = {}
}
In the above example, I understand that the override keyword is optional; but is it advisable? On which side of the terseness vs. safety trade-off should I fall?
override does one thing for you there: when removing Tooth.ache but not its implementations later on, you will get compiler errors. In particular, this forces implementations of Tooth (written by yourself or others) to be "close" to Tooth in a certain sense, namely that deprecated methods vanish (or are at least reconsidered).
This may or may not be desired.
Personally, when I see
override def whatever()
the first thing I think is, "I wonder how this was supposed to behave before?"
Since this is an unhelpful thought if it was an abstract method, I find it both more terse and more safe to leave it off.
I usually don't use override when implementing an abstract method. It's not wrong, but redundant, and I prefer to keep my code as short as possible while maintaining clarity. But I realize it's not a clear-cut case.
I always use it, to indicate member that were declared on super classes, even if abstract.

Can I create a collection in Scala that uses different equals/hashCode/compare implementations?

I'm looking for as simple way to create an identity set. I just want to be able to keep track of whether or not I've "seen" a particular object while traversing a graph.
I can't use a regular Set because Set uses "==" (the equals method in Scala) to compare elements. What I want is a Set that uses "eq."
Is there any way to create a Set in Scala that uses some application-specified method for testing equality rather than calling equals on the set elements? I looked for some kind of "wrapEquals" method that I could override but did not find it.
I know that I could use Java's IdentityHashMap, but I'm looking for something more general-purpose.
Another idea I had was to just wrap each set element in another object that implements equals in terms of eq, but it's wasteful to generate tons of new objects just to get a new equals implementation.
Thanks!
Depending on your needs you could create a box for which you use identity checks on the contained element such as:
class IdentBox[T <: AnyRef](val value: T) {
override def equals(other: Any): Boolean = other match {
case that: IdentBox[T] => that.value eq this.value
case _ => false
}
override def hashCode(): Int = value.hashCode
}
And make the collection to contain those boxes instead of the elements directly: Set[IdentBox[T]]
It has some overhead of boxing / unboxing but it might be tolerable in your use case.
This is a similar question. The accepted answer in that case was to use a TreeSet and provide a custom Comparator.
Since you don't require a reference to the "seen" objects, but just a boolean value for "contains", I would suggest just using a mutable.Set[Int] and loading it with values obtained by calling System.identityHashCode(obj).
Scala custom collections have enough conceptual surface area to scare off most people who want a quick tweak like this.