第一课 Scala光速入门

第一课 Scala光速入门

王家林_DT大数据梦工厂http://blog.sina.com.cn/s/blog_686c3cfb0102w4uz.html

要点速记

def sum(numbers : Int*) = { var result  = 0; for(element <- numbers) result += element; result} 

sum(1 to 100) // erro 1 to 100 => range
sum(1 to 100: _*) //correct

过程: 没有返回值的函数

def morning(content : String){println("Good " + content)}
def morning(content : String): Unit "Good " + content  //no return

lazy 只在调用时执行

val arr = new Array[Int](5)
=> Array[Int] = Array(0,0,0,0,0)
val arr1 = Array(0,0,0,0,0)  //use the apply method, the same result

Array 不可边长 ArrayBuffer可边长

import scala.collection.mutable.ArrayBuffer

arr = arrBuffer.toArray
arrBuffer = arr.toBuffer

+= 在尾部追加
yield
map

val arr2 = Array(1,1,3,4,10,11,100)
val arr3 = for(i <- arr2 ) yield i*i
arr2.filter(_%3 == 0).map(i => i*i)

.getOrElse("***",#)

作业一: 移除一个数组中第一个负数后的所有负数


val array = Array(1,-2,2,-1,-3,4)
var key = false
val idx = for(i <- 0 until array.length if !false || array(i) >= 0) yield {
    if (array(i) < 0) key  = true
    i
}
for(t <- 0 until idx.length) {array(t) = array(idx(t))}
array.trimEnd(array.length = idx.length)

你可能感兴趣的:(scala,大数据)