2016-01-24 72 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'是个好主意 –

相关问题