scala基础操作

1.apply的用法

scala> val array= Array(1,2,3,4)
array: Array[Int] = Array(1, 2, 3, 4)

scala> val array= Array。apply(1,2,3,4)
array: Array[Int] = Array(1, 2, 3, 4)

两句代码的效果一样

2.表达式本身就有返回值

val result = if (age>1) "aaa" else "ccc"
scala> result
res8: String = aaa

3.循环

var i = 0
while (i<=100){
  println(i)
  i+=1
}

for(i<- 0 to 100) println(i)

两句代码的效果一样

for(i<- 0 to 100 if i%2 ==0) println(i)

终止循环需要import Break模块
import scala.util.control.Breaks._

导入math函数后可以使用 如max min等函数
import scala.math._
min(1,2)

4.函数的变长参数

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

scala> sum (1,2,3,4,5)
res2: Int = 15

: _* 表示1100的每个元素提取出来
scala> sum (1 to 100 : _*)
res5: Int = 5050

4.函数与过程

函数:有返回值
scala> def morning(content :String) = "Good "+content
morning: (content: String)String

过程:没有返回值的函数
scala> def morning1(content :String) {println("Good "+content)}
morning1: (content: String)Unit

5.异常

try{
  val content = fromFile("/usr/local/spark/")
}catch{
  case _: Exception =>println("file not found")
}finally {
  println("bye")
}

5.集合

scala> import scala.collection.mutable.ArrayBu
ArrayBuffer   ArrayBuilder

scala> import scala.collection.mutable.ArrayBuffer
import scala.collection.mutable.ArrayBuffer

scala> val arrBugger = ArrayBuffer[Int]()
arrBugger: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer()

scala> arrBugger+=10
res11: arrBugger.type = ArrayBuffer(10)

scala> arrBugger+=10
res12: arrBugger.type = ArrayBuffer(10, 10)


scala> for (a <- arrBugger) println(a)
10
2
2
12
15

5.Map

scala> val person = Map("spark" -> 6,"spark" ->7)
person: scala.collection.immutable.Map[String,Int] = Map(spark -> 7)

scala> person
res26: scala.collection.immutable.Map[String,Int] = Map(spark -> 7)

scala> person("spark")
res27: Int = 7

scala> val person1 = scala.collection.mutable.Map("spark" -> 6,"spark" ->7)
person1: scala.collection.mutable.Map[String,Int] = Map(spark -> 7)

scala> person1 +=("flink"->3)
res30: person1.type = Map(spark -> 7, flink -> 3)

scala>  person1 -= "flink2"
res30: person1.type = Map(flink1 -> 3, spark -> 7, flink -> 3)

5.条件判断

以下判断两种方式效果一样
scala> person1
res39: scala.collection.mutable.Map[String,Int] = Map(flink1 -> 3, spark -> 7, f
link -> 3)

scala> val find = if(person1.contains("spark")) person1("spark") else 100
find: Int = 7

scala> val find = person1.getOrElse("spark" ,100)
find: Int = 7

增强for循环
scala> for((key,value)<-person1) println(key+"   "+value)
flink1   3
spark   7
flink   3

5.tuple多个类型一起的类型

scala> val tuple1 =("spark",1,11)
tuple1: (String, Int, Int) = (spark,1,11)

scala> tuple1._1
res42: String = spark
阅读更多
文章标签: scala spark
上一篇hadoop、spark相关概念
下一篇scala基础操作2
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭