加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

scala – 为什么不能重载没有参数的方法,对于隐式类

发布时间:2020-12-16 08:44:58 所属栏目:安全 来源:网络整理
导读:我尝试在对象世界使用隐式中重载方法 ?世界级 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("li
我尝试在对象世界使用隐式中重载方法
?世界级

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解决这个问题:

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

方法重载通常会在某些时候导致痛苦和痛苦.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读