scala教程 – spark应用之scala语言编程入门(二)
附送国内scala镜像下载地址:http://distfiles.macports.org/scala2.10/
//函数:
scala> def num3(number:Int*)={var retult=0;for(element <- number) retult += element;retult}num3: (number: Int*)Intscala> num3(3,3,4,5)
res0: Int = 15
scala> num3(1 to 100: _*)
res6: Int = 5050
scala> def morning(element :String)=”Good”+element
morning: (element: String)String
scala> morning(“morning”)
res0: String = GOodmorning
//过程:
scala> def morning(element :String){println(“GOod”+element)}
morning: (element: String)Unit
scala> def morning(element :String): Unit= “GOod”+element
morning: (element: String)Unit
文件读取
scala> import scala.io.Source._
import scala.io.Source._
scala> var content = fromFile(“/tmp/1.txt”).mkString
content: String =
“sd
”
异常处理
scala>java.io.FileNotFoundException
scala> try{
| var content = fromFile(“/tmp/31.txt”).mkString
| }catch{
| case _: FileNotFoundException => println(“File not found”)
| }finally{
| print(“bye bye “)
| }
数组
scala>var arr = new Array[Int](5)
arr: Array[Int] = Array(0,0,0,0,0)
scala> arr(3)
res0:Int = 0
scala> arr(3)=8
scala> arr
res2: Array[Int] = Array(0,0,0,8,0)
可变数组
import scala.collection.mutable.ArrayBuffer
scala> buf += (1,3,3,4,4)
res3: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(10, 1, 3, 3, 4, 4)
scala> buf
res4: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(10, 1, 3, 3, 4, 4)
scala> buf ++= Array(1,2,3,4)
res5: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(10, 1, 3, 3, 4, 4, 1, 2, 3, 4)
scala> buf.trimEnd(2)
scala> buf
res7: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(10, 1, 3, 3, 4, 4, 1, 2)
scala> for(i<-buf)println(i)101234扩展阅读://数组内置的快速排序 scala.util.Sorting.quickSort(a)
//移除最后的三个元素
numArrayBuffer.trimEnd(4);
//移除开始的两个元素
numArrayBuffer.trimStart(4);
//插入 在第2个位置插入100
numArrayBuffer.insert(2,100);
//移除 从3开始移除,移除4个
numArrayBuffer.remove(3,4);