为什么隐式defs需要implicitConversions而不是类? [英] Why implicitConversions is required for implicit defs but not classes?

查看:31
本文介绍了为什么隐式defs需要implicitConversions而不是类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我了解,隐式转换可能会导致代码难以理解,或者代码存在其他问题(甚至可能是错误?),这就是为什么它们需要显式启用才能在代码中使用而不会收到警告.

As far as I understand, implicit conversions can result in potentially hard to understand code, or code suffering from other problems (perhaps even bugs?), which is why they require explicit enabling in order to be used in code without getting warnings.

但是,鉴于隐式转换在很大程度上(如果不是大部分时间)用于用另一种类型的对象包装对象,隐式类也是如此 - 如果我是,我会很感激你纠正我错了——为什么前者需要导入 scala.language.implicitConversions 而后者不需要?

However, given that implicit conversions are in big part (if not most of the time) used for wrapping an object with an object of another type, and so are implicit classes—I'd appreciate you correcting me if I'm wrong—, why do the former require the import of scala.language.implicitConversions but the latter do not?

object Main extends App {
  implicit class StringFoo(x: String) {
    def fooWithImplicitClass(): Unit =
      println("foo with implicit class")
  }
  // => silence.

  "asd".fooWithImplicitClass()

  /************************/

  class Foo(x: String) {
    def fooWithImplicitDef(): Unit =
      println("foo with implicit def")
  }
  implicit def string2Foo(x: String) = new Foo(x)
  // => warning: implicit conversion method string2Foo should be enabled

  "asd".fooWithImplicitDef()
}

推荐答案

隐式类仅有效地添加新方法(或特征),并且仅在调用这些添加的方法时才使用它们(或显式使用隐式类,但这在实践中很少发生).另一方面,对现有类型的隐式转换可以在程序员不可见的情况下调用.

Implicit classes effectively only add new methods (or traits), and they are only ever used when these added methods are called (or the implicit class is used explicitly, but this rarely happens in practice). Implicit conversions to existing types, on the other hand, can be invoked with less visibility to the programmer.

这篇关于为什么隐式defs需要implicitConversions而不是类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆