Next Steps in Scala

1 Parameterize arrays with types

var big = new java.math.BigInteger("12345")

Parameterization means "configuring" an instance when you create it

var greetStrings = new Array[String](3)

greetStrings(0) = "Hello"
greetStrings(1) = ", "
greetStrings(2) = "world!\n"

for (i <- 0 to 2)
    print(greetStrings(i))

注意这一行:

for (i <- 0 to 2)

If a method takes only one parameter, you can call it without a dot or parentheses. The to in this example is actually a method that takes one Int argument. The code 0 to 2 is transformed into the method call (0) to (2)

greetStrings(0) = "Hello"

will be transformed into:

greetStrings.update(0, "Hello")

所以,刚才的代码等价于:

var greetStrings = new Array[String](3)

greetStrings.update(0, "Hello")
greetStrings(1, ", ")
greetStrings(2, "world!\n")

for (i <- 0.to(2))
    print(greetStrings.apply(i))

A more verbose way to call the applymethod is:

var numNames2 = Array.apply("zero", "one", "two")

2 Use Lists

val oneTwo = List(1, 2)
var threeFour = List(3, 4)
var oneTwoThreeFour = oneTwo ::: threeFour

:: pronounced "cons", Cons prepends a new element to the beginning of an existing list and returns the resulting list.

:: prepends a single item whereas ::: prepends a complete list. So, if you put a List in front of :: it is taken as one item, which results in a nested structure.

val list1 = List(1,2)
val list2 = List(3,4)

then

list1::list2 returns:

List[Any] = List(List(1, 2), 3, 4)

list1:::list2 returns:

List[Int] = List(1, 2, 3, 4)

48 页:列表

2 Use Tuples

Like lists, tuples are immutable, but unlike lists, tuples can contain different types of elements.

var pair = (99, "Luftballons")
println(pair._1)
println(pair._2)

3 Use Sets and Maps

var jetSet = Set("Boeing", "Airbus")
jetSet += "Lear"
println(jetSet.contains("Cessna"))

If you want a mutable set:

import scala.collection.mutable

val movieSet = mutable.Set("Hitch", "Poltergeist")
movieSet += "Shrek"
println(movieSet)

An immutable HashSet:

import scala.collection.immutable.HashSet

val hashSet = HashSet("Tomatoes", "Chilies")
println(hashSet + "Coriander")

You can create and initialize maps using factory methods similiar to those used for arrays, lists, and sets:

import scala.collection.mutable

val treasureMap = mutable.Map[Int, String]()
treasureMap += (1 -> "Go to island.")
treasureMap += (2 -> "Find big X on ground.")
treasureMap += (3 -> "Dig.")
println(treasureMap(2))

If you prefer an immutable map, no important is necessary, as immutable is the default map:

var romanNumeral = Map(
    1 -> "I",
    2 -> "II",
    3 -> "III",
    4 -> "IV",
    4 -> "V"
)
println(romanNumeral(4))

4 Learn to recognize the functional style

def printArgs(args: Array[String]): Unit = {
    var i = 0
    while (i < args.length) {
        println(args(i))
        i += 1
    }
}

You can transform this bit of code into a more functional style by getting rid of the var:

def printArgs(args: Array[String]): Unit = {
    for (arg <- args)
        println(arg)
}

or this:

def printArgs(args: Array[String]): Unit = {
    args.foreach(println)
}

5 Read lines from file 读取文件

import scala.io.Source

if (args.length > 0) {
    for (line <- Source.fromFile(args(0)).getLines())
        println(line.length + " " + line)
} else {
    Console.err.println("Please enter filename")
}

results matching ""

    No results matching ""