4

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?

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

You're right, Foo():String works. That's not really desirable though - the whole idea is to simply the calling code. What I really want to say is "I'm calling the version of this argument that takes zero type parameters, not the version that takes one type parameter".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.