簡體   English   中英

為什么不能重載沒有參數的方法,對於隱式類

[英]why can not overload no argument method ,for 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")
  }


}

//測試

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()
    ^

看起來像一個錯誤,但很難說。 通常,您將在單個隱式類中定義所有這些方法。 但是你遇到了錯誤,接受List兩個方法都有相同的擦除,編譯器不會允許它。 但是,您可以使用DummyImplicit解決這個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

方法重載通常會在某些時候導致痛苦和痛苦。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM