object FirstScala extends App { var a =""; val array = Array(1,2,3); array.foreach{arg=> a+=(arg+"")} print(a) if (array.length>0) a=a.substring(0, array.length-1) println(a) }
从上述代码中能够看出,在array.foreach方法中能够函数做为其参数,arg=>a+=(arg+"")是一个匿名参数。java
定义匿名函数:函数
val cube = (x:Int)=>x*x*x val c = cube(3)
定义内部函数:
spa
def sum_of_square(x:Int,y:Int):Int={ def square(x:Int):Int={ x*x } square(x)+square(y) }
构造函数scala
构造函数不是特殊的方法,和java有点区别,他是除了类方法之外的代码。
code
class Calculator(brand: String) { /** * A constructor. */ val color: String = if (brand == "TI") { "blue" } else if (brand == "HP") { "black" } else { "white" } // An instance method. def add(m: Int, n: Int): Int = m + n }
从上面能够看出Calculator构造函数定义了一个变量color,然而他直接用的是if表达式,可见表达式在scala中占了很大比重继承
特质:是一些字段和行为的集合,能够经过with字段进行扩展,和extends区别
get
trait Car { val brand: String }trait Shiny { val shineRefraction: Int }class BMW extends Car { val brand = "BMW"} class BMW extends Car with Shiny { val brand = "BMW" val shineRefraction = 12}
特质与抽象类的区别:string
特质不接受构造函数参数,因此你想使用构造函数初始化类,那你能够使用抽象类。trait Car(name:String)是不合法的it
若是不须要构造参数,能够优先选用特质,由于特质能够进行多扩展,而只能继承一个抽象类
io
特质支持泛型:
trait Cache[K, V] { def get(key: K): V def put(key: K, value: V) def delete(key: K) }
scala函数是有值的,这直接决定了scala中函数能够做为一个参数使用