Spark/Scala的一点入门材料,希望能对想快速了解的人有所帮助,对自己则是一个备忘。

Scala极速入门

如果需要一些感性认识,可以先读一读Scala的官方介绍。简单地说,Scala是一种更偏函数式的函数式、命令式的混合编程语言,同时也是面向对象的,函数是顶级对象,运行在Java虚拟机上,能与Java无缝结合。

package com.xiaomi.data.ctr.feature.analysis

/**
* Scala极速入门材料,可以直接贴入ScalaIDE的worksheet
*/

object test {
println("Welcome to the Scala worksheet") //> Welcome to the Scala worksheet
//val(ue) 是引用不变,不能改变val值变量的『值』
val n = 8 //> n : Int = 8
//n += 1 : value += is not a member of Int

//var(riable) 是变量,能用val用val,技穷用var
var nn = 7 //> nn : Int = 7
nn += 1
nn //> res0: Int = 8

//tuple - 使用得非常重的数据结构,同python,但是不能(显式地)按下标取到每个元素
val t = (1, "a", None) //> t : (Int, String, None.type) = (1,a,None)
t._1 //> res1: Int = 1
t._2 //> res2: String = a
t._3 //> res3: None.type = None
//纯语法,相信看过就不会忘记的
val (no, name, score) = t //> no : Int = 1
//| name : String = a
//| score : None.type = None

//collections, 取下标用()
val list = List(1, 2, 3) //> list : List[Int] = List(1, 2, 3)
list(0) //> res4: Int = 1
val m = Map(
"a" -> 1,
"c" -> 2,
"b" -> 3,
"d" -> 4) //> m : scala.collection.immutable.Map[String,Int] = Map(a -> 1, c -> 2, b -> 3
//| , d -> 4)
//取前两个
m.take(2) //> res5: scala.collection.immutable.Map[String,Int] = Map(a -> 1, c -> 2)
m("a") //> res6: Int = 1
//删除一个键,得到一个新的map
m - "a" //> res7: scala.collection.immutable.Map[String,Int] = Map(c -> 2, b -> 3, d ->
//| 4)

//函数:变量名在前、类型在后,函数头到函数体之间有“=”号
def isPalindrome(str: String) = (str == str.reverse.toString())
//> isPalindrome: (str: String)Boolean
//函数:可以显式指定返回值类型,函数的返回值就是最后一行的值
def isPalindromeDetail(str: String): Boolean = {
println(str)
str == str.reverse.toString
} //> isPalindromeDetail: (str: String)Boolean

def isPalindromeDetailUn(str: String): Boolean = ???
//> isPalindromeDetailUn: (str: String)Boolean
//函数式编程:map/filter/reduce,其它的基本都是变种
val ab = List(1, 2, 3, 4, 5, 6) //> ab : List[Int] = List(1, 2, 3, 4, 5, 6)
//每个元素乘3
ab.map(_ * 3) //> res8: List[Int] = List(3, 6, 9, 12, 15, 18)
//取出偶数
ab.filter(_ % 2 == 0) //> res9: List[Int] = List(2, 4, 6)
//reduce实现sum
ab.reduce(_ + _) //> res10: Int = 21
//reduce实现max
ab.reduce((x, y) => if (x > y) x else y) //> res11: Int = 6
}