1 库函数
import scala.math._ import scala.math._
2 函数定义
def 函数名(参数)=(函数体)
函数的定义用 def 和=,大括号可以不要,参数要指明类型(:Int)
定义hello函数:
scala> def hello(name:String)={
| println("hello " + name)
| }
定义加法函数:
scala> def add(x:Int,y:Int):Int={
| x+y
| }
add: (x: Int, y: Int)Int
scala> add(1,2)
res6: Int = 3
Scala函数可以没有return 语句,默认返回最后一个值
如果函数的参数在函数体内只出现一次,则可以使用下划线代替
例: def mul(x:Int,y:Int)=x*y 等同于 def mul=(_:Int)*(_:Int)
scala> def mul(x:Int,y:Int)=x*y
mul: (x: Int, y: Int)Int
scala> mul(3,2)
res8: Int = 6
scala> def mul=(_:Int)*(_:Int)
mul: (Int, Int) => Int
scala> mul(3,4)
res9: Int = 12
默认参数:
def hello(name:String="nobody")=println("hello " + name)
变长参数:
scala> def hello(names:String*)={
| for(i <- names) println("hello " + i)
| }
scala> hello("tom","jerry","dog")
hello tom
hello jerry
hello dog
scala>
匿名函数:
匿名函数格式:
var 变量名 = (参数:类型) => 函数体
加一函数:
scala> var addOne = (x:Int) => x+1
scala> addOne(2)
res14: Int = 3
(x: Int) => x + 1定义了一个匿名函数,=>表示对左边的参数进行右边的加工
此函数等同于 def addOne(x:Int):Int=x+1
综上,乘法函数的正常函数、匿名函数如下:
def mul(x:Int,y:int):Int=x*y
等同于
def mul = (x:Int,y:Int) =>x*y
等同于
def mul=(_:Int)*(_:Int) //下划线可以替代只出现一次的参数
偏函数 case:
scala> var x = 1 to 10
x: scala.collection.immutable.Range.Inclusive = Range(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
scala> x.map{ case a => 2*a }
res1: scala.collection.immutable.IndexedSeq[Int] = Vector(2, 4, 6, 8, 10, 12, 14, 16, 18, 20)
访问修饰符:
Scala 访问修饰符:private,protected,public。
如果没有指定,默认是 public。
Scala 中的 private 限定符,比 Java 更严格,在嵌套类情况下,外层类甚至不能访问被嵌套类的私有成员。
private:私有
用 private 关键字修饰,带有此标记的成员仅在包含了成员定义的类或对象内部可见,同样的规则还适用内部类。
for循环:
for( a <- 1 to 10){ println( "Value of a: " + a ); }
for循环配合yield:
for循环中的 yield 会把当前的元素记下来,保存在集合中,循环结束后将返回该集合。
scala> for (i <- 1 to 5) yield i
res10: scala.collection.immutable.IndexedSeq[Int] = Vector(1, 2, 3, 4, 5)