- scala複雜數據類型的基本使用
- 類,對象,函數: class,object, def …
- scala集合:模擬map-reduce
part1: scala 數組/集合基礎
Array | List,Set | Map | Tuple1…20 | |
---|---|---|---|---|
創建容器 | Array(1,2,3) | List(1,2,3) / Array(1,2,3).toList | Map(“k1”->“1”,“k2”->“2”) | scala.Tuple3(1,2,3)/ (1,2,3) |
取出元素 | arr(0), arr(1) | list(0),list(1) | map(“k1”) | tup._1, tup._2 |
常用函數 | size, sum,min, max,toList, flatMap | sortBy,reverse,toMap,flatMap,groupBy,reduce | map,mapValues,groupBy,filter |
part2: class,object,函數
函數
//for循環
for(i<-1 to 9){
for(j <-1 to 9){
if(i>=j){
printf("%d * %d = %d \t", j,i,(j*i))
}
}
println()
}
import scala.util.control.Breaks._
for(i<- 1 to 9; j<- 1 to 9){
if(i>=j){
printf("%d * %d = %d \t", j,i,(j*i))
}else {
if(j>i) {println() ; return}
}
}
for(i<-"hello"){
println(i)
}
//while循環
var x=5
while( x>0){
println(x)
x-=1
}
//線程調用
def thread( f:()=>Unit )={
new Thread(){
override def run()={
f()
}
}.start()
}
def f ={
while(true)
println("a")
Thread.sleep(100)
}
thread(() => println("hello"))
//求解: 直線方程
def f( x1:Int,y1:Int, x2:Int, y2:Int ):Int=>Int = {
k=(y2-y1)/(x2-x1)
b=y1-k*x1
def fun(x:Int)={
k*x+b
}
fun _
}
f(1,2,3,4)(5)
part3: 類,對象,函數
//類
class Person(var name:String, var age:Int) {
//重寫構造
def this(){
this("lisi",23)
}
//自動生產: get,set
}
//類:伴生對象--單例模式:靜態方法
object Person{
def sayHello(p:Person ): Unit ={
println(p.name+","+p.age)
}
}
//啓動入口===============================
object AppTest{
def main(args: Array[String]): Unit = {
Person.sayHello(new Person())//lisi,23
}
}