2016-01-24 75 views
4
隱類

我嘗試在重載對象的方法世界使用隱 類世界爲什麼不能重載無參數方法,爲

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

不要使用重載...通常這不是一個好主意。你想通過超載來實現什麼? –

+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 = [email protected] 

scala> world.world() 
world 

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

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

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

+0

謝謝,使用'DummyImplicit'是個好主意 –

相關問題