CHAPTER 2
Type Less, Do More
7. Literals
Integer Literals整数文字
123,0xFF, 013, 123L
Long, Int, Short, Char, Byte
Floating-Point Literals
0.12 3.0e+5 0.1f 0.1d
Float, Double
Boolean Literals
true false
Boolean
Character Literals
'A', '/n'
Char
String Literals
"test"
多行字符串
"""test
test
test"""
Symbol Literals
'id // scala.Symbol("id")
8. Tuples元组
val t1 = ("Hello", 1, 2.3)
def tuple1(x: Int, y: Int, z: Int) = (x*x, y*y, z*z) //返回一个元组
val t = tuple1(1,2,3)
println(t._1) //start from 1
val (x,y,z) = tuple1(1,2,3) //当返回多个值时很有用
9. Option, Some, and None: Avoiding nulls
When there is no value, use None, an object that is a subclass of Option. When there is a value, use Some, which wraps the value. Some is also a subclass of Option.
val m = Map("1" -> "test1")
m.get("1").get
m.get("2").getOrElse("Oops")
10.Organizing Code in Files and Namespaces
File names don’t have to match the type names, the package structure does not have to match the directory structure.
尽管可以这样,我还是觉得遵从Java的规则比较好。
//Java风格
package com.test
class MyClass {
// ...
}
//嵌套式
package com {
package test {
class class1 {
}
}
}
11. Importing Types and Their Members
import java.awt._
import java.io.File
import java.io.File._ //相当于 static import
import java.util.{Map, HashMap} //有选择的import
def writeAboutBigInteger() = {
import java.math.BigInteger.{
ONE => _,
TEN,
ZERO => JAVAZERO }
println( "TEN: "+TEN )
println( "ZERO: "+JAVAZERO )
}
writeAboutBigInteger()
First, we can put import statements almost anywhere we want, not just at the top of the file, as required by Java.
The second feature shown is the ability to rename imported items.
import scala.collection.mutable._
import collection.immutable._ // Since "scala" is already imported
import _root_.scala.collection.jcl._ // full path from real "root"
package scala.actors {
import remote._ // We're in the scope of "scala.actors"
}To create an absolute path, start with _root_.
13. Abstract Types And Parameterized Types
val languages: List[String] = ... //use [], not <>
class List[+A].
The + in front of the A means that List[B] is a subtype of List[A] for any B that is a subtype of A.
If there is a - in front of a type parameter, then the relationship goes the other way;
Foo[B] would be a supertype of Foo[A], if the declaration is Foo[-A].
import java.io._
abstract class BulkReader {
type In
val source: In
def read: String
}
class StringBulkReader(val source: String) extends BulkReader {
type In = String
def read = source
}
class FileBulkReader(val source: File) extends BulkReader {
type In = File
def read = {
val in = new BufferedInputStream(new FileInputStream(source))
val numBytes = in.available()
val bytes = new Array[Byte](numBytes)
in.read(bytes, 0, numBytes)
new String(bytes)
}
}
println( new StringBulkReader("Hello Scala!").read )
println( new FileBulkReader(new File("abstract-types-script.scala")).read )
14. Reserved Words
To avoid a compilation error, surround the name with single back quotes, e.g., java.util.Scanner.‵match‵.