SCALA入门(5)

数组
package com.scala.study

import scala.io.Source
import scala.collection.mutable.ArrayBuffer

object HelloScala {
  def main(args: Array[String]) {
    var nums = new Array[Int](10)
    var strings = new Array[String](10)
    var s = Array("hello", "world")
    s(0) = "good bye"
    val b = ArrayBuffer[Int]()
    b += 1
    b += (1, 2, 3, 4)
    b ++= Array(8, 13, 21)
    b.trimEnd(5)
    b.remove(2)
    b.insert(2, 1, 2)
    for (i <- 0 until b.length) println(i)
    val c = Array(2, 3, 4, 5, 6)
    //创建数组
    val result = for (elem <- c) yield 2 * elem
    for (elem <- c if elem % 2 == 0) yield 2 * elem
    c.filter(_ % 2 == 0).map(2 * _)
    Array(1, 2, 3, 4, 5, 6).sum
    ArrayBuffer("fdsf", "fdsfds").max
    ArrayBuffer(1, 2, 3, 4).sorted
    var e = Array("a", "b")
    e.mkString("and")
    e.mkString("<", ",", ">")
    scala.util.Sorting.quickSort(e)

    var matrix = Array.ofDim[Double](3, 4)
    matrix(2)(1) = 42
    var triangle = new Array[Array[Int]](10)
    for (i <- 0 until triangle.length)
      triangle(i) = new Array[Int](i + 1)
  }
}

Map,Tuple,Zip
package com.scala.study

import scala.io.Source
import scala.collection.mutable.ArrayBuffer

object HelloScala {
  def main(args: Array[String]) {
    //Map不可变
    val map = Map("book" -> 10, "gun" -> 18, "ipad" -> 1000)
    for ((k, v) <- map) yield (k, v * 0.9)
    //可变Map
    val sortedScore = scala.collection.mutable.Map("hello" -> 10, "world" -> 100)
    val helloScore = sortedScore.getOrElse("earth", 100);
    println(helloScore)
    sortedScore += ("earth" -> 200)
    sortedScore -= "hello"
    val tuple = (1, 2.2, "2323", "34")
    val third = tuple._3
    val third1 = tuple _3
    var (first, second, forth, _) = tuple
    "Rocky Spark".partition(_.isUpper)
    val symbols = Array("[", "-", "]")
    val counts = Array(2, 5, 2)
    val pairs = symbols.zip(counts)
  }
}

Scala私有字段
package com.scala.study

import scala.io.Source
import scala.collection.mutable.ArrayBuffer

object HelloScala {
  class Person {
    //对象私有属性
    private var age = 0
    private[this] var privateAge= 0
    def increment() { age += 1 }
    def current = age
    def isYounger(other:Person) = age < other.age
  }
  class Student {
    private var privateage = 0
    def age = privateage
    val name = "Scala"
  }
  def main(args: Array[String]) {
    val person = new Person()
    person.increment()
    person.increment()
    println(person.current)
    val student = new Student
    println(student.age)

  }
}

猜你喜欢

转载自v-ger.iteye.com/blog/2304356
今日推荐