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

smac89
  • 39,374
  • 15
  • 132
  • 179
  • 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? – Luis Miguel Mejía Suárez Jan 28 '20 at 01: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. – som-snytt Jan 28 '20 at 01:52
  • 2
    You inspired a bug report: https://github.com/scala/bug/issues/11866 – som-snytt Jan 28 '20 at 04:07
  • @som-snytt Oh dam, that's an interesting bug report – smac89 Jan 28 '20 at 06:07

0 Answers0