10.4 隐式类
在 scala2.10 后提供了隐式类,可以使用implicit
声明类,隐式类的非常强大,同样可以扩展类的功能,比前面使用隐式转换丰富类库功能更加的方便,在集合中隐式类会发挥重要的作用。
10.4.1 隐式类的几个特点
其所带的构造参数有且只能有一个
隐式类必须被定义在“类”或“伴生对象”或“包对象”里,即隐式类不能是顶级的(
top-level objects
)。隐式类不能是
case class
样例类(case class在后续介绍)作用域内不能有与之相同名称的标示符
object ImplicitDemo3 {
def main(args: Array[String]): Unit = {
implicit class DB1(var m : Mysql1){
def addSuffix(): String ={
m + " scala"
}
def sayOk(): Unit ={
println("db1 sayOk ...")
}
}
val mysql: DB1 = new Mysql1
mysql.sayOk()
println(mysql.addSuffix())
}
}
class Mysql1{
def syaOk(): Unit ={
println("sayOk...")
}
override def toString: String = "mysql1-tostring..."
}
另一个案例:
package day02.implicitclass
object DateHelper {
implicit class DateHelper(val day: Int) {
import java.time.LocalDate
def days(when: String) = {
val today: LocalDate = LocalDate.now
if (when == "ago") {
today.minusDays(this.day)
} else {
today.plusDays(this.day)
}
}
}
def main(args: Array[String]): Unit = {
val ago = "ago"
val from_now = "from_now"
val past = 2 days ago // 2.days(ago)
val future = 5 days from_now // 5.days(from_now)
println(past)
println(future)
}
}