后续补充
/**
* Created by dengy on 2017/12/18.
*/
object grammarPractise {
def main(args: Array[String]) { //=======================================================//
def fun(str1: String, str2: String) = {
str1 + "\t" + str2
} println( fun("spark", "hadoop") ) //spark hadoop val add = (str1:String, str2:String)=> str1+ "\t" +str2 println(add("spark", "hadoop")) //spark hadoop def g( f:(String,String)=>String ,str1:String,str2:String)={
val line = f(str1,str2)
println(line)
} g(add, "Spark", "Hadoop") //spark hadoop //这个确实一中 调用的办法, 是 传 函数的一种办法。三个结果都是: Spark Hadoop
//=======================================================// // 变量的 集合中的变量
val list = List.range(1,10)
println( list.mkString("[","\t","]")) //[1 2 3 4 5 6 7 8 9] val list2 = list.filter( ( x:Int )=> x%2==0 )
println( list2.mkString("[","\t","]") ) //[2 4 6 8] val list3 = list.filter(x=>x%2==0)
println(list3.mkString("[","\t","]")) //[2 4 6 8] val list4 = list.filter(_%2==0)
println(list4.mkString("[","\t","]")) //[2 4 6 8] //=======================================================// // 传递函数
val sayHello:()=> Unit = () =>println("hello") def g1(f:()=>Unit,num:Int)={
for(i<-1 to num)f()
}
g1(sayHello,5) // 5个 hello //=======================================================// //传递String参数
def saySomething(str1:String)= (str2:String) => println( str1+"\t"+str2 ) val aa:String=>Unit=saySomething("spark") aa("hadoop") //spark hadoop //=======================================================// var standardAge = 20
val aa1 = (age:Int)=> age>=standardAge //这个最后是个boolean型
println(aa1(22)) //true def g2( f:Int=>Boolean, age:Int):Unit={ //注意这里的写法
println( f(age) )
}
g2(aa1,22) //true
standardAge = 23
g2(aa1,22) //false ,注意,这里调用的aa1中standardAge,已经被改了,所以为false //=======================================================//
//调用函数,实现加法
var more = 10
val x=(one:Int)=>one+more
println(x(20)) //30
more=20
println(x(20)) //40 //=======================================================// //foreache 累加
var sum = 0
val array = Array(10,20,30)
array.foreach(f=> sum=sum+f )
println(sum) //=======================================================// }
}