Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is method overloading not defined for different return types?

In Scala, you can overload a method by having methods that share a common name, but which either have different arities or different parameter types. I was wondering why this wasn't also extended to the return type of a method? Consider the following code:

class C {
  def m: Int = 42
  def m: String = "forty two"
}

val c = new C
val i: Int = C.m
val s: String = C.m

Is there a reason why this shouldn't work?

Thank you,

Vincent.

like image 672
gnuvince Avatar asked Oct 17 '09 16:10

gnuvince


People also ask

Why methods are not overloaded based on return type?

The compiler does not consider the return type while differentiating the overloaded method. But you cannot declare two methods with the same signature and different return types. It will throw a compile-time error. If both methods have the same parameter types, but different return types, then it is not possible.

Can we overload method with different return type?

Method overloading cannot be done by changing the return type of methods. The most important rule of method overloading is that two overloaded methods must have different parameters.

Why is method overloading not possible by changing the return type in Java?

Q) Why Method Overloading is not possible by changing the return type of method only? In java, method overloading is not possible by changing the return type of the method only because of ambiguity.

Why method overloading is not possible by changing the return type of method only Mcq?

Core Java bootcamp program with Hands on practiceIt is not possible to decide to execute which method based on the return type, therefore, overloading is not possible just by changing the return type of the method.


1 Answers

Actually, you can make it work by the magic of 'implicit'. As following:

scala> case class Result(i: Int,s: String)

scala> class C {
     |     def m: Result = Result(42,"forty two")
     | }

scala> implicit def res2int(res: Result) = res.i

scala> implicit def res2str(res: Result) = res.s

scala> val c = new C

scala> val i: Int = c.m

i: Int = 42


scala> val s: String = c.m

s: String = forty two

scala>
like image 130
Eastsun Avatar answered Nov 16 '22 03:11

Eastsun