4

Given the following trait and companion object definitions:

trait Api {
  def foo(s: String): String
}

object Api extends Api {
  override def foo(s: String) = s
}

I would like to extend the companion object's foo method to have a property function and for that, I use the following implicit class:

implicit class ExtendApi(api: Api.type) {
  object foo {
    def asInt(s: String): Int = s.toInt
  }
}

println (Api.foo.asInt("1")) // Does not work

However, using this does compile. I get an error:

missing argument list for method foo in object Api
Unapplied methods are only converted to functions when a function type is expected.
You can make this conversion explicit by writing `foo _` or `foo(_)` instead of `foo`.

It seems scala is not resolving the implicit definition to find the foo object.

I tried to be explicit by writing:

println (implicitly[Api.type].foo.asInt("1"))

Now I get another error:

could not find implicit value for parameter e: Playground.this.Api.type

This new error does not make sense to me.

Is what I am trying to do possible? How can I fix the errors? Thank you.

Scastie Link

4
  • The Scala compiler will never chose an extension method over a normal one. Also, I am not sure you can use an inner object as an extension method. Why do you need this? Commented Jan 28, 2020 at 1:05
  • 1
    It will prefer the extension with a different signature; inner object with apply is OK for extension (because it's just looking for a member), but with the same name, spec 7.3 says only methods are eligible. Commented Jan 28, 2020 at 1:52
  • 2
    You inspired a bug report: github.com/scala/bug/issues/11866 Commented Jan 28, 2020 at 4:07
  • @som-snytt Oh dam, that's an interesting bug report Commented Jan 28, 2020 at 6:07

0

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.