1 class OldStudent
extends Student {
2
3 def filterName(s: String, f: String => String) =
{
4 if (s !=
null) f(s)
else s
5 }
6
7 def mytrim(s: String) =
s.trim()
8
9 def talkToAll(p1Name: String, p2Name: String, p3Name: String, fn: (String, String, String) => String): String =
{
10 fn(p1Name, p2Name, p3Name)
11 }
12
13 def talkToAllCommon[A, B](p1Name: A, p2Name: A, p3Name: A, fn: (A, A, A) => B): B =
{
14 fn(p1Name, p2Name, p3Name)
15 }
16
17 def talkToAllCommon2[A, B, C](p1Name: A, p2Name: B, p3Name: C, fn: (A, B, C) => C): C =
{
18 fn(p1Name, p2Name, p3Name)
19 }
20
21 }
22
23 object FunctionDemo2 {
24 def main(args: Array[String]): Unit =
{
25 val s =
new OldStudent()
26 //高阶函数
27 println(s.filterName(
null, s.mytrim))
28 println(s.filterName("bill"
, s.mytrim))
29 //匿名函数
30 val greeter = (name: String) => s"Hello, $name"
31 println(greeter("world"
))
32 //无参函数
33 def writeStart() = "write start"
34 val writeStartVal = () => "write start val"
35 println(writeStart)
36 println(writeStartVal())
37 //高阶函数匿名调用
38 println(s.filterName(
null, (s: String) =>
s.trim()))
39 println(s.filterName("bill", (s: String) =>
s.trim()))
40 println(s.filterName(
null, s =>
s.trim()))
41 println(s.filterName("bill", s =>
s.trim()))
42 //占位符
43 println(s.filterName(
null, _.trim()))
44 println(s.filterName("bill"
, _.trim()))
45 //多占位符
46 println(s.talkToAll("bill", "allen", "sky", _ + ", " + _ + ", " +
_))
47 //类型参数
48 println(s.talkToAllCommon[String, String]("bill", "allen", "sky", _ + _ +
_))
49 println(s.talkToAllCommon[Int, Int](1, 2, 3, _ + _ +
_))
50 println(s.talkToAllCommon2[Int, Float, Double](1, 2, 3, _ + _ +
_))
51 }
52 }
null
bill
Hello, world
write start
write start val
null
bill
null
bill
null
bill
bill, allen, sky
billallensky
6
6.0
转载于:https://www.cnblogs.com/AK47Sonic/p/7071065.html
相关资源:JAVA上百实例源码以及开源项目