Why dont languages allow overloading of methods by return value?

前端 未结 8 641
[愿得一人]
[愿得一人] 2021-01-02 08:38

c, java and many other languages do not pay attention to return values.

int   i = func()
float f = func()
int   func() { return 5 }
float func() { return 1.3         


        
8条回答
  •  天命终不由人
    2021-01-02 09:31

    What about this case?

    class A implements Foo { /*...*/ }
    class B implements Foo { /*...*/ }
    
    A func() { return new A(); }
    B func() { return new B(); }
    
    Foo v = func(); // which do you call?!
    

    There are already problems with ambiguity when you allow overloading of a single function name that take different arguments. Having to check the return type as well would probably make resolving the right function a lot harder.

    I'm sure a language could implement that, but it would make things a lot more complicated, and would generally make the code harder to understand.

提交回复
热议问题