scala学习笔记(9): 语法续

1 不定长参数

def sum(args: Int*) = {
        var result = 0
        for ( arg <- args) result += arg
        result
}

2 数组初始化

val nums = new Array[Int](10)
    nums: Array[Int] = Array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0)

val nums1 = Array(1, 2, 4)
    nums1: Array[Int] = Array(1, 2, 4)

3 变长数组

import scala.collection.mutable.ArrayBuffer

val b = new ArrayBuffer[Int]()
    //b: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer()

b += 1
    // 添加元素到末尾
    res9: b.type = ArrayBuffer(1)
    
b += (2, 3, 4)
    // 添加多个元素用括号
    res10: b.type = ArrayBuffer(1, 2, 3, 4)

val a = 5 to 10
    a: scala.collection.immutable.Range.Inclusive = Range(5, 6, 7, 8, 9, 10)

b ++= a
    // 添加其他类型
    res11: b.type = ArrayBuffer(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

4 应用于Array、ArrayBuffer的算法

scala> val a = Array(1, 7, 2, 4, 5)
//a: Array[Int] = Array(1, 7, 2, 4, 5)

scala> a.sorted
//res18: Array[Int] = Array(1, 2, 4, 5, 7)

scala> a.sortWith(_ < _)
//res19: Array[Int] = Array(1, 2, 4, 5, 7)

scala> a.sortWith(_ > _)
//res20: Array[Int] = Array(7, 5, 4, 2, 1)

5 数组的mkString

scala> val a = Array(1, 7, 2, 4, 5)
    //a: Array[Int] = Array(1, 7, 2, 4, 5)

scala> a.mkString(" and ")
    //res21: String = 1 and 7 and 2 and 4 and 5

scala> a.mkString("[", ",", "]")
    //res22: String = [1,7,2,4,5]

  

 

posted on 2016-07-11 20:57  月下之风  阅读(178)  评论(0编辑  收藏  举报

导航