Marcus Downing
Marcus Downing

Reputation: 10141

Overloading a method based on a type parameter

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

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

Calling it with a type parameter is fine:

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

But calling it without a type parameter doesn't 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()

It's not a runtime problem, so adding an implicit dummy parameter doesn't help. Nor does having a restricted parameter (Foo[Unit]()). Is there any way of doing this that isn't ambiguous to the compiler?

Upvotes: 4

Views: 313

Answers (1)

Moritz
Moritz

Reputation: 14212

You are effectively overloading on the return type. While neither Scala nor Java let you normally let you do so in this case it happens.

Foo() : String will work in this case but it remains questionable though if overloading on the return type is desirable.

Upvotes: 2

Related Questions