简体   繁体   中英

why can not overload no argument method ,for implicit class

i try to overload method in object World use implicit class World

class World {
}

object World {

  implicit class WithWorld(_world: World) {
    def world(): Unit = println("world")
  }

  implicit class WithWorld2(_world: World) {
    def world(i: List[Int]): Unit = println("list Int")
  }

  implicit class WithWorld3(_world: World) {
    def world(i: List[String]): Unit = println("list String")
  }


}

//test

val world = new World()

//this is right

world.world(List(1))
world.world(List("string"))

//but this world.world() ,i get a compile error

Error:(36, 5) type mismatch;
 found   : world.type (with underlying type World)
 required: ?{def world: ?}
Note that implicit conversions are not applicable because they are ambiguous:
 both method WithWorld in object World of type (_world: World)World.WithWorld
 and method WithWorld2 in object World of type (_world: World)World.WithWorld2
 are possible conversion functions from world.type to ?{def world: ?}
    world.world()
    ^

Seems like a bug, but it's difficult to tell. Normally you would define all these methods in a single implicit class. But then you run into the error where both methods that accept a List have the same erasure and the compiler won't allow it. However, you can work around that using a DummyImplicit :

class World

object World {

  implicit class WithWorld(_world: World) {
    def world(): Unit = println("world")
    def world(i: List[Int]): Unit = println("list Int")
    def world(i: List[String])(implicit d: DummyImplicit): Unit = println("list String")
  }

}

scala> val world = new World
world: World = World@4afcd809

scala> world.world()
world

scala> world.world(List(1, 2, 3))
list Int

scala> world.world(List("a", "b", "c"))
list String

Method overloading usually leads to pain and suffering at some point.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM