//定义函数,参数数带有默认值
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:_*)
//过程,没有=的函数,
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 += 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中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")
看菜鸟教程吧,讲真的这个东西有点无聊。