1. 程式人生 > >【未完成】Scala 基礎

【未完成】Scala 基礎

-s 調用 end 使用 sum 延遲計算 ++ com 1.2


0. 說明


1. 基本概念

  1.0 Scala是什麽

  Scala 是一門多範式的編程語言,設計初衷是要集成面向對象編程和函數式編程的各種特性。

  1.1 變量 & 常量

  在 Scala 中,使用關鍵詞 "var" 聲明變量,使用關鍵詞 "val" 聲明常量。

# 變量,可以對值進行更改
var a = 10

# 常量,不能更改
val a = 10

  1.2 函數 & 類的區別

  1. 函數,不需要使用類,直接調用
  2. 方法需要通過類調用

  1.3 產生1 ~ 10的序列
  1 to 10 相當於 1.to(10)
  技術分享圖片

  1.4 字符串交集

  "hello".intersect("world")

  技術分享圖片

  1.5 BigInt 類型

  var b = BigInt(999999)

  1.6 Scala 自增

  Scala 不像 Java 那樣使用 a++ a-- 作為自增自減

  而是使用以下

  a += 1
  a -= 1

  1.7 使用函數

  導入 math 下的所有成員


  import scala.math._
  sqrt(2)      //開方
  pow(2,3)    //冪函數

  技術分享圖片

  1.8 apply 方法

  "hello".apply(0)
  "hello"(0)

   技術分享圖片

  1.9 表達式

  val x = 2
  val b = if(x > 0 ) 1 else -1    // Scala中不包含三元運算

  技術分享圖片

  // b:AnyVal = ()
  val b = if(x < 0) -1

  val x:Unit = ()       //相當於null

  技術分享圖片

  1.10 語句整體
  val b = if(x > 0 ){1
  }else -1

  1.11 粘貼

  :paste
  ctrl + d    //退出粘貼模式

  1.12 語句終止

  同一行多條語句之間用 " ; " 分隔

  val b = {println("a") ;println("bbb");100}

  技術分享圖片

  1.13 輸出 & 輸入

  // 輸出
  println("xxx")
  printf("aaa %s bb %s" , "abc" , "def")

  技術分享圖片

  // 輸入,讀取控制臺輸入
  var name = readLine("請輸入名字:")
  println(name)

  技術分享圖片

2. 循環

  2.1 while 循環

var n = 0 ;
while(n < 10){
println(n)
n +=1
}

  技術分享圖片

  2.2 for 循環

for(i <- 1 to 10){
println(i)
}

  技術分享圖片

  2.3 使用 while 和 for 輸出 99 表格

var r = 1
while(r < 15){
var c = 1
while(c <= r){
printf("%dx%d=%d\t" , c , r , (c * r))
if(c == r) println()
c+=1
}
r +=1
}

//for循環
for(i <- 1 to 9){
for(j <- 1 to i){
printf("%dx%d=%d\t" , j , i , (i * j))
if(i == j)println()
}
}

//until, 1 ~ 9
val a = 1 until 10

//break和continue
import scala.util.control.Breaks._
for(i < 1 to 10){
println(i)
break ;
}

//高級for循環 , 迪爾卡積
for(i <- 1 to 9 ; j <- 1 to i){
printf("%dx%d=%d\t" , j , i i * j)
if(i == i)println()
}

//守衛條件for循環
for(i <- 1 to 9 ; j <- 1 to i if( i == 2 * j)){
printf("i=%d,j=%d\r\n" , i , j)
}

//yield ,產生新集合
for(i <- 1 to 5) yield i * 2

//定義函數
def add(a:Int,b:Int):Int = a + b

//定義函數,實現n的階乘
5! = 5 x 4x 3x 2x 1 ;
def fac(n:Int) = {
var r = 1
for(i <- 1 to n){
r *= i
}
r
}

//遞歸函數必須顯式定義返回類型
def fac(n:Int):Int = if(n == 1) 1 else n * fac(n - 1)

//定義函數,參數數帶有默認值
def decorate(prefix:String="{{{" , str:String , suffix:String="}}}") = {
prefix + str + suffix
}
//帶名參數
decorate(str = "hello" )


//變長參數
def add(x:Int*) = {var sum = 0 ;for(i <- x)sum += i ;sum}
add(1,2,3,4,5)
add(1 to 5:_*) //把range對象打散成數字序列,1,2,3,4,5

//過程,沒有=的函數,
def out(){println("hello world")}

//lazy,延遲計算
val x = 1/ 0
lazy val x = 1 / 0
x

//定義數組 [泛型]
val arr = new Array[Int](10)
arr(0) = 1
arr(1) = 2
arr(2) = 3
for(i <- 0 until arr.length ) arr(i) = i + 1

val arr = Array[String]("hello","world")
val arr = Array("hello","world")
val arr = Array.apply("hello","world")
val arr = Array.apply[String]("hello","world")

val arr = Array[Int](100) //一個100的值
val arr = new Array[Int](100) //100個0

//命名法則:
//++ 加多個元素
//+ 加一個元素
//+= =表示修改自身的內容


//數組緩沖區(集合)
//=修改自身的內容,否則生成新集合
import scala.collection.mutable.ArrayBuffer
val buf = ArrayBuffer[Int](1,2,3)
val x = buf.++(4 to 10)
buf.++=(4 to 10)
buf.+=(1,2,3,4) //追加多個元素
buf += 12
buf.trimEnd(3) //移除末尾3個元素
buf.insert(0,-2,-1,0) //在指定的索引位置,插入數字序列
buf.toArray()

//倒序遍歷
for(i <- (0 until buf.length).reverse) println(buf(i))

//常用操作
buf.sum

//mkStrig,連接元素成串
buf.mkString(",")
buf.mkString("{{{" ,"," , "}}}")

//多維數組
val arr = new Array[Array[Int]](2)
val arr = Array.ofDim[Int](3,4)

//java集合和scala buffer之間的互操作
val list:java.util.List[String] = new java.util.ArrayList[String]()
list.add("hello")
list.add("world")


//定義函數,使用java的list類型
def mylist(list:java.util.List[String]) = println(list.size())
val buf = ArrayBuffer[String]("how" , "are" , "you")
mylist(buf) //類型不匹配
import scala.collection.JavaConversions.bufferAsJavaList
mylist(buf) //ok


//定義scala參數緩沖區的函數
def mybuf(buf:scala.collection.mutable.Buffer[String]) = println(buf.size())
import scala.collection.JavaConversions.asScalaBuffer //隱式轉換
mybuf(list);


//映射map,不可變
val map = Map(1->"tom" , 2->"tomas" , 3->"tomasLee")
map(1)
map(2)
map(3)

//可變集合,導類指定別名
import scala.collection.mutable.{Map=>MMap}
val map = MMap(1->"tomas" , 2->"tomasLee")
map(1)

//對偶是一個kv對,等價於java Map中Entry.
val c = 100->"tomas"
val c = (100 , "tomas")

//map
val map = MMap(("001","tom"),("002","tomas"),("003","tomasLee"))

//叠代map
for(k <- map.keys) println(k)
for(v <- map.values) println(v)
for((k,v) <- map) println(k + " : " + v)
for(c <- map) println(c._1 + " : " + c._2)

//
map.contains("001")
val v = map.getOrElse("001" , "nobody")
map.+=(( "006", "tom6"))
map.+=("006"->"tom6")
map.-=("006")

val m1 = scala.collection.immutable.SortedMap(1->"tom1" , 3->"tom3",2->"tom2")
for(c <- m1) println(c)

//元組tuple
val t = ( 1,,"tom",12)
val t:Tuple3[Int,String,Int] = new Tuple3[Int,String,Int](1 , "tom",12) ;
t._1
t._1 = 100 //錯的,元組的組員是不能重新賦值

//拉鏈 zip
val ids = (1,2,3)
val names= ("tom1" , "tom2", "tom3")
ids.zip(names)
ids.zipAll(names,-1, "nobody") //全拉鏈,-1左邊填充元素,"nobody"右側填充元素


技術分享圖片

【未完成】Scala 基礎