Why dont languages allow overloading of methods by return value?

前端 未结 8 520
[愿得一人]
[愿得一人] 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:17

    Yes, allowing overloading on return types complicates a language. It complicates the resolving of overloaded identifiers (e.g. function names). But it isn't impossible, e.g. Haskell allows to overload function based on their return type.

    class Num a where
      fromInteger :: Integer -> a 
      ...
    

    Num is a type class in Haskell with a method called fromInteger which is a function from an arbitrary size Integer to an arbitrary type which has an instance of Num. The Haskell type class mechanism is rather different from the class concept of object-oriented languages. Therefore my explanation might sound strange.

    But, the result is I can use the function fromInteger and, depending on the calling context, different implementations are chooen at compile time.

    There is a whole line of research on type systems, which made this feature possible. Therefore, I'd say it is doable in statically typed languages. Dynamically typed languages would either require time-travelling or some clever ideas.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题