我尝试在对象世界使用隐式中重载方法 世界级
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()
//这是对的
world.world(List(1))
world.world(List("string"))
//但是这个world.world()
,我得到了一个编译错误
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()
^
答案 0 :(得分:1)
看起来像一个错误,但很难说。通常,您将在单个隐式类中定义所有这些方法。但是你遇到了错误,接受List
的两个方法都有相同的擦除而编译器不会允许它。但是,您可以使用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
方法重载通常会在某些时候导致痛苦和痛苦。