Method overload based on type parameter

I would like to have a method that can be called with or without a type parameter, and return a different value for each. Here are some obviously simplified code:

object Foo { def apply() = "Hello" def apply[T]() = 1 } 

A call with a type parameter is fine:

 scala> Foo[String]() res1: Int = 1 

But calling it without a type parameter does not work:

 scala> Foo() <console>:9: error: ambiguous reference to overloaded definition, both method apply in object Foo of type [T]()Int and method apply in object Foo of type ()java.lang.String match argument types () Foo() 

This is not a run-time problem, so adding an implicit dummy parameter does not help. Also does not have a limited parameter ( Foo[Unit]() ). Is there a way to do this that is not ambiguous for the compiler?

+4
source share
1 answer

You really overload the return type. Although neither Scala nor Java allow you to do this normally, in this case it happens.

Foo() : String will work in this case, but remains doubtful, although overloading by return type is desirable.

+2
source

All Articles