直接上代码 注意点写在注释里了
//foldLeft(x)(option)表示对该数组从左往右开始遍历,依次和x做option操作
//如下函数表示,对input数组(input:Int* 表示可变参数)进行挑选最大值操作
//还可以这样写(1 to 100).foldLeft(0)(_+_)表示对数组(1 to 100)进行累加操作
//foldRight就是从右往左遍历
def function(input: Int*) = input.foldLeft(input(0))(Math.max)//Math.max外面的()改成{}也可以
println(function(1, 2, 3, 4, 5, 6, 7))
def fun(input:Array[String]): Unit =
{
input.foreach((x:String)=>if(x == "I")println(x))//input数组循环输出
}
val input : Array[String] = new Array[String](3) //Scala新建数组
input(0) = "I"
input(1) = "LOVE"
input(2) = "YOU"
fun(input)
input.sortWith(_>_).foreach(println) //将input数组排序后输出
for(i <- 0 until 2) println(i) //数组输出的另一种赋值,其中until 可以 换为to,两者区别就是前者不包含末尾,后者包含
//<- 可以理解为 in 可以如此用:input <- Set("test","good")