目录
摘要
隐式参数,隐式转换,DSL
隐式参数,隐式转换与 DSL
隐式参数
概述
隐式参数用于泛型中,在使用时可以不用每次都手动指定类型
使用
语法
implicit 参数
abstract class SemiGroup2[A] {
def add(x: A, y: A): A
}
abstract class Monoid2[A] extends SemiGroup2[A] {
def unit: A
}
def sum[A](xs: List[A])(implicit m: Monoid2[A]): A = if (xs.isEmpty) m.unit
else m.add(xs.head, sum(xs.tail))
implicit val stringMonoid = new Monoid2[String] {
def add(x: String, y: String): String = x.concat(y)
def unit: String = ""
}
implicit val intMonoid = new Monoid2[Int] {
def add(x: Int, y: Int): Int = x + y
def unit: Int = 0
}
// 如果没有使用隐式参数
sum(List("a", "bc", "def"))(stringMonoid)
sum(List(1, 2, 3))(intMonoid)
// 使用了隐式参数
sum(List("a", "bc", "def"))
隐式转换
概述
定义一个转换函数,可以在使用相应类型的时候自动转换。
使用
语法
implicit 方法定义
import java.text.SimpleDateFormat
implicit def strToDate(str: String) =
new SimpleDateFormat("yyyy-MM-dd").parse(str)
println("2013-01-01 unix time: " + "2013-01-01".getTime()/1000l) //2013-01-01 unix time: 1356969600
这个例子可以将 String
自动转换为 Date
类型。隐式转换是实现 DSL 的重要工具。
DSL
概述
DSL 是 Scala 最强大武器,可以使一些描述性代码变得极为简单。
使用
import java.util.Date
import org.json4s.JsonDSL._
import org.json4s.jackson.JsonMethods._
case class Twitter(id: Long, text: String, publishedAt: Option[java.util.Date])
var twitters = Twitter(1, "hello scala", Some(new Date())) ::
Twitter(2, "I like scala tour", None) :: Nil
var json = ("twitters"
-> twitters.map(
t => ("id" -> t.id)
~ ("text" -> t.text)
~ ("published_at" -> t.publishedAt.toString())))
println(pretty(render(json)))
这个例子是使用 DSL 生成 JSON。Scala 很多看似是语言级的特性也是用 DSL 做到的。