Scala 学习笔记之函数(2)

 class OldStudent extends Student {

   def filterName(s: String, f: String => String) = {
if (s != null) f(s) else s
} def mytrim(s: String) = s.trim() def talkToAll(p1Name: String, p2Name: String, p3Name: String, fn: (String, String, String) => String): String = {
fn(p1Name, p2Name, p3Name)
} def talkToAllCommon[A, B](p1Name: A, p2Name: A, p3Name: A, fn: (A, A, A) => B): B = {
fn(p1Name, p2Name, p3Name)
} def talkToAllCommon2[A, B, C](p1Name: A, p2Name: B, p3Name: C, fn: (A, B, C) => C): C = {
fn(p1Name, p2Name, p3Name)
} } object FunctionDemo2 {
def main(args: Array[String]): Unit = {
val s = new OldStudent()
//高阶函数
println(s.filterName(null, s.mytrim))
println(s.filterName("bill", s.mytrim))
//匿名函数
val greeter = (name: String) => s"Hello, $name"
println(greeter("world"))
//无参函数
def writeStart() = "write start"
val writeStartVal = () => "write start val"
println(writeStart)
println(writeStartVal())
//高阶函数匿名调用
println(s.filterName(null, (s: String) => s.trim()))
println(s.filterName("bill", (s: String) => s.trim()))
println(s.filterName(null, s => s.trim()))
println(s.filterName("bill", s => s.trim()))
//占位符
println(s.filterName(null, _.trim()))
println(s.filterName("bill", _.trim()))
//多占位符
println(s.talkToAll("bill", "allen", "sky", _ + ", " + _ + ", " + _))
//类型参数
println(s.talkToAllCommon[String, String]("bill", "allen", "sky", _ + _ + _))
println(s.talkToAllCommon[Int, Int](1, 2, 3, _ + _ + _))
println(s.talkToAllCommon2[Int, Float, Double](1, 2, 3, _ + _ + _))
}
}
null
bill
Hello, world
write start
write start val
null
bill
null
bill
null
bill
bill, allen, sky
billallensky
6
6.0
上一篇:Oracle 10g体系机构及安全管理《思维导图》


下一篇:利用HibernateTools从数据库表生成带注解的POJO