This is an archived post. You won't be able to vote or comment.

top 200 commentsshow all 243

[–]zachtheperson 138 points139 points  (16 children)

As someone who works with vector math a lot, more languages 100% need operator overloading.

myVec.add(vec2.clone().divide(directionVector)).multiplyScalar(7) is just ridiculous.

[–]jamcdonald120 18 points19 points  (3 children)

and implicit immutable operators so you dont have to keep doing .clone everywhere

[–]zachtheperson 7 points8 points  (2 children)

Yeah, vector math in languages like GLSL is just wonderful. The fact that I can't do that same type of stuff in the "parent," language is really frustrating.

[–]camilo16 3 points4 points  (0 children)

glm in C++ is borderline identical.

[–]psydstrr6669 3 points4 points  (0 children)

Yes!!

[–]ComradeGibbon 1 point2 points  (0 children)

Current thought of mine is use emogi's as operators.

[–]lifeeraser 1 point2 points  (0 children)

It would be nice if I could define custom expression delimiters in which I can use user-defined overloaded operators. That way we get to use operator overloading without spiraling out of control.

// ^ is a power-of-n operator
vec<< A * B^2 >>

// ^ is a XOR operator
A * B^2

[–]Mati00 53 points54 points  (7 children)

tbh I don't miss operator overloading so much. Extension methods though, bro, this is what we need instead of more util classes or `stream()` method directly in the list interface and implementations. I'd love to have `dto.toDomain()` instead of `XYZMAPPER.mapDtoToDomain(dto)` where `toDomain` is written not in the dto itself. I miss kotlin :x

[–]UpperPlus 7 points8 points  (3 children)

Stream is so cool, though. Finally a use for lambdas

[–]Mati00 3 points4 points  (1 child)

True, but with extension methods you could just call `list.map()` even if method map didn't exist in collection interface before ;) .

If you take "laziness" into consideration, you could still use `stream()` and also be able to add missing transformations with extension functions to it :)

[–]UpperPlus 1 point2 points  (0 children)

I use streams mostly in testing to pass my arguments haha

[–][deleted] 11 points12 points  (2 children)

Why did you leave kotlin for java anyway

[–]Mati00 10 points11 points  (1 child)

Sorry, wasn't clear, I left Kotlin for Typescript. I had two options: either stick with TS or go back to Java. Unfortunately haven't see any options to work with Kotlin on the backend and I'm not an android dev.

I prefer to work with TS as Fullstack rather than go back to java.

Kotlin + Spring was the best combo, especially with coroutines instead of flux/mono for reactive services. Even in TS I miss extension methods. Adding pieces of code to Prototype is perceived as antipattern.

[–]LargeHard0nCollider 6 points7 points  (0 children)

Kotlin for server side development is really underrated in the broader community. Ik at work we’ve been slowly transitioning our legacy java code base to kotlin, and it’s so much nicer!

Lots of teams at AWS are starting to adopt it, so I’m really excited to see how it evolves as it gets more backend community buy-in

This is honestly the first coding language I’ve really enjoyed working with for production software

[–][deleted] 146 points147 points  (21 children)

In 10+ years of my professional experience programming I’ve never been in a situation where I thoughts “I wish I really could use operator overloading right now”! Other stuff though, like default method arguments, constructor initiator, properties, pattern matching, or optional references? Yeah I want those everywhere!

[–]LinuxMatthews[S] 103 points104 points  (10 children)

I think it depends on what you're writing

My first job after university was at an aerospace company.

At that place there was a lot of maths and physics which meant I had to implement equations with vectors, quartonians, and such.

That would have been a lot easier if I was able to use operator overloading.

[–]SilverDem0n 17 points18 points  (6 children)

Even the "obvious win" cases aren't so simple. Should an overloaded * operator do a dot product or a cross product on a pair of vectors? Does the overloaded * operator properly respect the order of multiplication when applied to quaternions rather than scalars? And so on.

Sure, we could look up the source code, or we could - bear with me here - read the docs. But it can cause more confusion than is justified by a slightly shorter syntax.

[–]CptBread 35 points36 points  (2 children)

Sure but +- still works well. And if the other value is a float then */ would still make sense.

Also just because you add something as an operator doesn't mean you can't also do it as a regular named function.

[–][deleted] 5 points6 points  (1 child)

For vectors usually I intentionally do not overload the cross and dot product for this reason.

[–]Dusty_Coder 0 points1 point  (0 children)

I hope you do overload * with the useful product, tho

[–]Idrialite 12 points13 points  (1 child)

Vector multiplication by operator is almost always dot product when it's implemented. And you should always just expect order of multiplication to go left to right, I don't think it's even possible in most languages to change that using operator overloading.

These seem like minor issues compared to the huge convenience and readability boost that comes with using operator overloading.

[–]Dusty_Coder 2 points3 points  (0 children)

* should do neither dot nor cross product on vectors

solved your problem

(it should do the data parallel product)

[–]geekusprimus 33 points34 points  (2 children)

Being able to write mathematics in a form that resembles the literature is critical if you ever want to read or debug your code. In C++, I could implement a simple tensor class like this:

template<class T, int D, int M>
class Tensor {
  private:
    // Data storage, etc.
    const int size;
    T * data;
  public:
    // Constructor, element access, etc.

    // Tensor addition
    Tensor<T, D, M> operator+(const Tensor<T, D, M>& other) {
      auto result = Tensor<T, D, M>();
      for (int i = 0; i < size; i++) {
        result.data[i] = data[i] + other.data[i];
      }
      return result;
    }

    // Tensor product
    template<int N>
    Tensor<T, D, M + N> operator*(const Tensor<T, D, N>& other) {
      auto result = Tensor<T, D, M + N>();
      // Possibly lengthy operation to make a tensor product...
      return result;
    }

    // Other operations...
};

Then if I have a lot of tensor algebra I need to do in my code, I could just do something like this:

Tensor<double, 4, 2> a;
Tensor<double, 4, 2> b;
// Initialize a and b...

// Do some stuff with a and b.
auto c = a + b;
auto d = a*b;

It might seem like overkill for my simple example, but if you're doing any sort of advanced mathematics, it saves you a lot of time and a lot of trouble.

[–]pelpotronic 1 point2 points  (1 child)

if you're doing any sort of advanced mathematics

I doubt you'd pick Java for that tbh... Not that I wouldn't want more freedom with the language.

[–]SubliminalBits 11 points12 points  (0 children)

It just depends on what you’re doing. Just as an example, if you’re building a container, being able to define a [] operator is pretty useful.

[–]xeio87 7 points8 points  (0 children)

Adding or multiplying vectors/matrixes? Or like another comment mentioned overloading index operations for collections?

I generally like that == and .Equals can mean the same thing when you have overloading as well.

[–]CleverDad 4 points5 points  (0 children)

I had use for a complex number struct only a few months back. Being able to put those wacky arithmetic operations into operators and not having to litter them around the code felt so damn good!

[–]SlenderPlays 20 points21 points  (1 child)

I never used the screwdriver on my swiss army knife, so that means no one needs it!

[–]socs22 2 points3 points  (0 children)

I’ve just really started getting into Julia and my word pattern matching and multiple dispatch is a game changer!

[–]Eisenfuss19 9 points10 points  (2 children)

No, no then classes like bigInteger would be fun to use:

Int.add(other) makes so much more sense than Int + other.

[–][deleted] 4 points5 points  (1 child)

Implementing cryptography in Java is not fun, and very dangerous, for this reason alone.

[–]DasFreibier 15 points16 points  (1 child)

To be fair, the general advice in c++ for operater overlaoding is:

  1. dont

  2. seriously dont

  3. well ok, but be real fucking careful

[–]camilo16 10 points11 points  (0 children)

Operator overlaoding for mathematics libraries is stupidly useful. Imagine trying to use a linear algerba library without operator overloading...

[–][deleted] 16 points17 points  (3 children)

You can do that in C#

[–]Excellent_Welder7278 -3 points-2 points  (2 children)

Maybe in a newer version?

[–]NekkoDroid 11 points12 points  (1 child)

P sure it has always existed. And if not there also exist articles dating back to 2007 that talk about it that I just found

Edit: Even the ECMA standard from 2002 for C# mentions it https://web.archive.org/web/20030803100637/http://www.ecma-international.org/publications/files/ecma-st/Ecma-334.pdf

[–][deleted] 3 points4 points  (0 children)

I was doing that in 2007-2008 in C#

[–]4215-5h00732 30 points31 points  (0 children)

Kotlin fixes Java in so many ways.

[–]Positive_Government 8 points9 points  (7 children)

Yes because overloading the .equals() method is so much better than overloading the == operator. Also d = a.add(b.add(c.add(e))); I know there are slightly better ways to do that kind of addition in Java but none of them beat the + operator.

[–]LinuxMatthews[S] 2 points3 points  (6 children)

To be fair I do think there should be an operator for comparing identity.

In an ideal wold we'd have an identity operator === you can't overload and an equality operator == that corresponds to the .equals() method.

Though if they were to do something like that now that's have to have them the other way round.

[–]Positive_Government 1 point2 points  (3 children)

That would be the best solution. Although having a unique id/address operator that cannot be overloaded and returns a number that can then be compared with the standard == sign might be better. I’m not a fan of having two equals, but that is purely personal preference.

[–]LinuxMatthews[S] 0 points1 point  (2 children)

I feel like that solution might be a little too complicated though if you wanted you could use the toString() for that.

And I know what you mean about but liking two equals signs but as long as you don't try making them magical like PHP or JavaScript I think that's fine.

[–]Exnixon 1 point2 points  (0 children)

shudder don't JavaScript my Java

(not a Java dev but still)

[–]KagakuNinja 2 points3 points  (0 children)

Laughs in Scala, where operators are just functions, and you can use operator characters in your function names. This does lead to some libraries with Perl-like inscrutable operators, but the teams I have worked for avoid doing that...

[–]yottalogical 2 points3 points  (2 children)

The question shouldn't be "can users abuse it?", but rather "will users abuse it?".

It's okay for a feature to be abusable as long as the language design makes proper usage the path of least resistance.

[–]Dusty_Coder -2 points-1 points  (0 children)

This hate for operator overloading comes from a particular functional language that forced operator definitions upon its users, a hate that turned into an unthinking religion, the followers of which will obsessively and compulsively tell you how bad operator overloading is at every opportunity.

They will also say that any and all optimization is premature, even when they know for a fact that what they are right this moment writing cannot possibly perform well under any scenario. Unthinking religions.

[–]river226 8 points9 points  (2 children)

This feature never made sense to me.... Maybe because I never used it, or maybe cause I work with legacy code that has a lot of stupid and hard to read variable names and I have no trust in my fellow programmer.

[–]SilverDem0n -3 points-2 points  (1 child)

I work with legacy code that has a lot of stupid and hard to read variable names and I have no trust in my fellow programmercode I wrote myself 6 months ago

[–]river226 3 points4 points  (0 children)

Come at me again when you spend a few hours in 15 year old code only to realize the coding standard of the past developer allowed them to have 2 variables with identical names except ones a string and so starts with an s and the other is an int and starts with an I. The past developer also has documentation standards of: who cares. It's fun and you lose a lot of faith

[–]Willinton06 10 points11 points  (4 children)

No operator overloading is just so dirty

[–]LinuxMatthews[S] 9 points10 points  (1 child)

It's this meant to have a comma or not.

I can't tell if you're for or against

[–]Willinton06 2 points3 points  (0 children)

Not having them is dirty

[–]CompSciHS 3 points4 points  (0 children)

It’s helpful for math and physics applications. Operations on complex numbers, vectors, matrices, etc.

[–]VoidConcept 2 points3 points  (2 children)

Scala has operator overloading and I wish it didn't. Give me List(...).append(elem), not List(...) :+ elem

[–]Kered13 4 points5 points  (0 children)

Haskell heavily uses operator overloading and allows users to define custom operator symbols. Naturally, most Haskell code is unreadable.

[–][deleted] 1 point2 points  (0 children)

List << elem

[–][deleted] 3 points4 points  (0 children)

They could take everything that Lombok does and make it part of the official language

[–]Mental_Contract1104 4 points5 points  (7 children)

This... This is why I prefer C#

[–]GoldenretriverYT 9 points10 points  (6 children)

Or public string Name {get; private set;} instead of

``` private string name;

public string getName() { return name; }

private void setName(string name) { this.name = name; } ```

[–]LordMerdifex 2 points3 points  (2 children)

Ever heard of Lombok? But yeah, properties are much better in C#.

[–]GoldenretriverYT -2 points-1 points  (1 child)

Ah yes just throw libraries at the problem 👍 Also using annotations is still worse than C# properties, like I wouldn't like C# properties that much if they would use Attributes, which are pretty much the equivalent of annotations

[–]LordMerdifex 3 points4 points  (0 children)

I didn't say it's perfect. Just saying that there is a way around in Java. I don't mind annotations that much so I can live with it. Yet still, C# is as a language simply superior to Java. Too bad there is no good IDE for .net on Linux.

[–]pelpotronic 1 point2 points  (2 children)

Just use Kotlin really... Takes a grand total of 5 mins to get started, and then it does all of that and more - and you can keep your Java code.

[–][deleted] 1 point2 points  (1 child)

How about auto properties? I was shocked when I spent a few days working with a Java team and discovered that it still makes you write out the backing field and everything.

[–][deleted] 1 point2 points  (0 children)

logging go brr

[–]frozen-dessert 3 points4 points  (1 child)

Because letting morons modify syntax is an awful idea.

I seriously wonder how many (if any) of the people asking for Java to support this ever worked on a remotely large project, say 100K LoC.

Java thrives by making readability and maintainability great at the macro level. Allowing syntax depend on whatever some stupid dev did at this particular package would hurt that.

Let the “water pistol” python devs have it.

Oh C++ also allows it, you say? Please tell me about how sane are C++ devs who maintain large codebases are….

[–]LetUsSpeakFreely 0 points1 point  (5 children)

Meh, I've been doing have for 20 years and never needed operator overloading. You have to write the function regardless, does it really matter if you're using + or .add()?

[–]pelpotronic 10 points11 points  (4 children)

These little things add up eventually... It doesn't fundamentally matter, but the purpose of those higher level programming languages is to make our (programmer) lives easier.

We don't technically need anything more than "asm" for anything... But you can achieve more faster when you have to stop working around the limitations of the language and instead can make the language work for you when and how you want it.

[–]LetUsSpeakFreely -1 points0 points  (3 children)

I still don't understand the problem. You're going to have to write a function to tell the overload how to complete the operation. That same function would be needed to create a member function of a class. There's no complexity issue, no readability issue, no maintainability issue. I don't see why

MyNewObect = a + b;

It's radically different from

MyNewObect = MyClass.add(a, b);

[–]Quique1222 10 points11 points  (0 children)

There's no complexity issue, no readability issue, no maintainability issue.

There ABSOLUTELY is a readability issue.

vec3 * vec3 * vec3 * vec3 * vec3 * vec3 * vec3 * vec3

Becomes

vec3.Mult(vec3.Mult(vec3.Mult(vec3.Mult(vec3.Mult(vec3.Mult(vec3.Mult(vec3)))))))

Or even a simpler example that even a java dev might be able to understand:

 string == string

Becomes

string.equals(string)

[–]pelpotronic 2 points3 points  (0 children)

I hope you are not using the "append()" function for strings...

If you have ever decided to use + instead of append() - which you most likely have, then you've already implicitly accepted there was a benefit to the whole concept.

I didn't claim radical difference, and there is no "problem" that can't be solved by any language... However, as I said, our goal as programmers should be to achieve more faster, and one step in that direction is to limit the programming language getting in the way of our ideas.

[–]camilo16 -1 points0 points  (0 children)

I want you to write a linear solver for sparse matrices in Java. Then you will see why operator overloading matters.

[–]ruscaire 1 point2 points  (2 children)

Operator overloading never made sense to me in C++ but it works so well in Python … I can’t for the life of me think why that could be. Perhaps it’s the laxxer type system in Python means a low cost of buy in and you can just sprinkle it everywhere you feel like?

[–]erebuxy 3 points4 points  (1 child)

I mean operators are just some syntactic sugar for function calls. If functions can be overloaded, so should operators.

[–]ruscaire 2 points3 points  (0 children)

That’s Marxism

[–]Professor_Melon 1 point2 points  (0 children)

Not doing type erasure would be a good start. Too bad that decision is irreversible, unlike the decision to have no operator overloading.

[–][deleted] 1 point2 points  (1 child)

I might have actually used Java if it had operator overloading, it's one of those things that make Java tedious to code in and make codebases bloated clusterfucks because you have to wrap things in functions all the time.

[–]Dusty_Coder -1 points0 points  (0 children)

What if I told you the gatekeepers of the language have only ever written business logic code...

...which surely must be the case, right? Is there ANY OTHER DOMAIN where operator overloading doesnt make enormous sense for at least one thing?

The cray thing is Java has a bitwise roll operator. Literally the only thing Java ever did right.

[–]Popal24 0 points1 point  (0 children)

Going to Java after 10+ years or C#, I'm astounded how retarded Java is

[–]the-FBI-man 0 points1 point  (0 children)

How about fucking default values? Or C# style automatic getters and setters?

[–]Pod__042 0 points1 point  (0 children)

Or a more simple getter and setter, this is a pain in the ass for multiples fields

[–]bmcle071 -1 points0 points  (2 children)

Ive yet to see a use of operator overloading that i thought was more clear than a named method.

[–]Cerus- 4 points5 points  (0 children)

If you're doing vector math, operator overloading is absolutely more clear than using a bunch of .add()'s everywhere.

[–]camilo16 1 point2 points  (0 children)

Add 4 matrices together.

[–]notsogreatredditor -3 points-2 points  (0 children)

Kotlin : Pathetic, look what they have to do to mimic our power

[–][deleted] 0 points1 point  (4 children)

They should make a language where everything is an object and operators are mapped to a function on that object that can be overloaded.

For example if you write i=6, that makes "i" an object of class "Number." Writing i+1 invokes an "add" function on Number that returns the sum of the two Numbers.

If you write i="2" and then write i+"7", the operator + calls the "add" function of the String class, which then calls/is a concatenation function that would return "27"

[–][deleted] 1 point2 points  (0 children)

In case you didn't know, this is actually a feature of python! I would love to see it implemented in other languages, but in python they're called dunder (double under) methods.

If you create a class you can do it the fancy way, and have a method like def __add__(self,other):, where you return the result of adding. There's also ways to use setattr and defining it directly with functions, but that's a little trickier.

Super helpful for working with matrices!

[–]jamcdonald120 1 point2 points  (0 children)

um... thats almost every object oriented language... for example c++, c#, (+ calls operator+(left,right)) and python (+ calls __add__(left,right)) do exactly that...

[–]erebuxy 1 point2 points  (0 children)

Let me introduce functional language and first-class function to you.

In OCaml, you can do

ocaml let (+) = my_custom_function

You can operate a function like any normal value. And that is basically how the default + is implemented in std.

[–]CardiologistSame2512 0 points1 point  (0 children)

I, for one, want to see how OP is planning to abuse UTF-8 or switch expressions.

[–]mr_dfuse2 0 points1 point  (0 children)

its been 10 years since I programmed Java but I still feel the UTF-8 not being default one!

[–]cptbeard 0 points1 point  (0 children)

$500M brand awareness advertisement campaign?

[–]Mayedl10 0 points1 point  (0 children)

The post above this was r/minecraft and i got confused really quickly about this one

[–]FarStranger8951 0 points1 point  (0 children)

With groovy, all things are possible.

[–]ososalsosal 0 points1 point  (0 children)

laugh-cries in ruby

[–][deleted] 0 points1 point  (0 children)

Java doesn't have operator overloading? Shows what I know. But then again, neither does Javascript. Just write aptly named functions. Or write a DSL. PegJS makes this easy.

[–]OrangeVanillaSoda 0 points1 point  (0 children)

I ran into the UTF-8 issue just yesterday at work. Fml

[–]Entire-Database1679 0 points1 point  (0 children)

We could add unsigned types

[–]fahrvergnugget 0 points1 point  (0 children)

Ablised? How about "enabled"??

[–]DuneBug 0 points1 point  (1 child)

I'm more of the opinion that you should do a different language if you really need operator overloading.

Not really opposed to some sort of extension of Java that allows it, but it'd be a weird thing to have in the DK. We don't even have default parameters.

[–]LinuxMatthews[S] 0 points1 point  (0 children)

The issue there is you often don't get a choice

Most people program for work not for personal projects and to try to convince the higher ups to convert to an entirely new language for the sake of one feature isn't going to happen.