Scala2.10新特性之 Implicit classes

Implicit classes

隐式类

http://docs.scala-lang.org/sips/pending/implicit-classes.html

摘要

一个新的语法结构被提出,它简化了这种类——为另外一种类型提供扩展方法——的建立。 html

描述

implicit关键字如今容许做为类的注解来使用。若是一个类带有implicit关键字注解,那么它就是一个隐式类。
隐式类必须有一个(第一个参数列表中只有一个参数的)主构造器。它也能够包含额外的隐式参数列表。隐式类只能定义在容许定义方法的地方(不能在顶级)。隐式类是一个类与隐式方法配对的语法糖,隐式方法模拟类构造器。
生成的隐式方法与隐式类同名。这样容许用类名来导入隐式转换(后半句没看懂)(This allows importing the implicit conversion using the name of the class, as one expects from other implicit definitions)。例如,以下形式的定义:
implicit class RichInt(n: Int) extends Ordered[Int] {
    def min(m: Int): Int = if (n <= m) n else m
    ...
}
会被编译器转换成:
class RichInt(n: Int) extends Ordered[Int] {
    def min(m: Int): Int = if (n <= m) n else m
    ...
}
implicit final def RichInt(n: Int): RichInt = new RichInt(n)
隐式类上的注解,会默认附加到生成的类和方法上。例如:
@bar
implicit class Foo(n: Int)
会变成:
@bar implicit def Foo(n: Int): Foo = new Foo(n)
@bar class Foo(n:Int)
annotation.target注解被扩展成包含genClass和method注解。它用于规定给隐式类生成的类添加注解,仍是给生成的方法添加注解。例如:
@(bar @genClass) implicit class Foo(n: Int)
会变成:
implicit def Foo(n: Int): Foo = new Foo(n)
@bar class Foo(n: Int)

规范

不须要改变Scala的语法规范,相关的生产规则已经容许隐式类。
LocalModifier ::= ‘implicit’
BlockStat ::= {LocalModifier} TmplDef
TmplDef ::= [‘case’] ‘class’ ClassDef

语言规范SLS 7.1修改为容许在class上使用implicit修饰符。隐式类中新的部分,用来描述这种结构的行为。 scala

影响

新的语法不能破坏现有的代码,因此保持源代码兼容现有的技术。 翻译

2013-1-25 这篇比较短,有些话英文很好理解,但硬翻译成中文很别扭。
相关文章
相关标签/搜索