1. 程式人生 > >scala 中List的簡單使用

scala 中List的簡單使用

main 列表 fix decorator head != 簡單 mut println

/**
  * scala 中List的使用
  *
  */

object ListUse {

  def main(args: Array[String]): Unit = {

    def decorator(l:List[Int] , prefix:String){
      if(l != Nil) {
        println(prefix + l.head)
        decorator(l.tail , prefix)
      }
    }

    // List 是不可變的列表
    val list = List(1,2,3,4,5,6,7)
    decorator(list, "list=")

    // LinkedList 是可變列表
    // 使用elem引用頭部,使用next引用尾部
    val ll = scala.collection.mutable.LinkedList(1,2,3,4,5)
    println(ll.elem)
    println(ll.next) // 尾部所有的

    val ll2 = scala.collection.mutable.LinkedList(1,2,3,4,5)
    var currentList = ll2
    while (currentList != Nil){
      currentList.elem = currentList.elem * 2
      currentList = currentList.next
    }
    println(ll2) // LinkedList(2, 4, 6, 8, 10)
    // 改變的還是ll2


  }

}

  

scala 中List的簡單使用