Scala 学习笔记之函数

Posted AK47Sonic

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Scala 学习笔记之函数相关的知识,希望对你有一定的参考价值。

 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 }

 

以上是关于Scala 学习笔记之函数的主要内容,如果未能解决你的问题,请参考以下文章

Scala学习笔记一之基础语法,条件控制,循环控制,函数,数组,集合

Scala 学习笔记之隐式参数和隐式转换并用

Scala学习笔记(函数相关)

Scala学习笔记及与Java不同之处总结-从Java开发者角度

Scala语言学习笔记

Scala之option类型及偏函数使用异常处理正则表达式