Scala学习笔记1

 

Programming Scala 

CHAPTER 2 

 

    Type Less, Do More

 

 

1.  Semicolons分号
不需要在语句最后加分号,如: println("test")
一行中有多个语句可以用分号隔开,如:val str="abc"; println(str)
一个语句可以断成多行,scala可以根据上下文情况判断一个语句是否结束。所以,需要在合适的地方断开。如:
println("abc" +
"def")

2.  Variable Declarations变量声明
immutable(read-only) val str1: String = "abc"
mutable(read-write)    var str2: String = "abc"
简写
val str1 = "abc"
var str2 = "abc"

3.  Method Declarations方法声明
def methodname1(v1: String, v2: Int): String = { .... } //一般形式
def methodname2(v1: String, v2: Int): String    //abstract
def methodname3(v1: String)(v2: Int): String = { .... }  //currying methods

4.  Method Default and Named Arguments (Scala Version 2.8)方法的缺省和有名参
def joiner(strings: List[String], separator: String = " "): String = 
    strings.mkString(separator)
println(joiner(List("a","b")))
println(joiner(strings = List("a","b")))
println(joiner(List("a","b"), separator=" "))

5.  Nesting Method Definitions嵌套的方法定义
def func1(n: Int): Unit = {
    def func2(i: Int): Unit = {     //只在func1内可见
        ...                           //可看见func1内的参数n,如果同名func2优先
    }

    func2(1)
}

6.  Inferring Type Information 推断类型信息
val str = "abc"
val map: Map[Int, String] = new HashMap
val map = new HashMap[Int, String]

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
不要使用null, null不是对象

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.

 


12.  Imports are Relative
use _, not *

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 means that List[B] is a subtype of List[A] for any 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].

 

 


Abstract Types的例子

import java.io._

 

abstract class BulkReader 

    type In

    val source: In 

    def readString

}

 

class StringBulkReader(val source: Stringextends BulkReader 

    type In String

    def read = source

}

 

class FileBulkReader(val source: Fileextends 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‵.


 

你可能感兴趣的:(scala,String,list,HashMap,import,Literals)