鲁春利的工作笔记,谁说程序员不能有文艺范?



Scala(http://www.scala-lang.org/)是基于JVM的即可以面向对象也可以面向过程的编程语言。

Scala的代码比Java简洁,但同样功能强大,http://www.scala-lang.org/documentation/api.html


1、环境准备 

    JDK:1.7.0_11
    Scala:2.11.0(下载地址:http://www.scala-lang.org/download/
    Scala IDE :使用Win64 Eclipse SDK

wKiom1ZzjxCBb2z8AADss-l3NBY699.jpg

    实际上对于未集成Scala开发环境的Eclipse,Scala也提供了插件的支持。

    http://scala-ide.org/download/current.html

    中提供安装地址:http://download.scala-ide.org/sdk/lithium/e44/scala211/stable/site

wKiom1ZzkLyQgZvsAAGlHl5uF60313.jpg

2、Hello World

    Scala IDE-->New-->Scala Project-->输入项目名称并选择需要的JRE
    选择项目-->New-->Scala Class-->代码如下

object HelloWorld {
  def main(args : Array[String]) {
     println("Hello World!");
  }
}
Run As-->Scala Application-->打印Hello World

    解压scala-2.11.0-M5.zip文件,并配置SCALA_HOME环境变量,在命令行窗口调用scala:

C:\Users\Administrator.ZGC-20130427XQA>scala
Welcome to Scala version 2.11.0-M5 (Java HotSpot(TM) 64-Bit Server VM, Java 1.7.0_11).
Type in expressions to have them evaluated.
Type :help for more information.
scala> object HelloWorld{
 |     def main(args:Array[String]) {
 |         println("Hello World!");
 |     }
 | };
defined object HelloWorld

scala> HelloWorld.main(null);
Hello World!

scala>

    可以通过:help查看帮助信息

scala> :help
All commands can be abbreviated, e.g. :he instead of :help.
:cp <path>               add a jar or directory to the classpath
:edit <id>|<line>        edit history
:help [command]          print this summary or command-specific help
:history [num]           show the history (optional num is commands to show)
:h? <string>             search the history
:imports [name name ...] show import history, identifying sources of names
:implicits [-v]          show the implicits in scope
:javap <path|class>      disassemble a file or class name
:line <id>|<line>        place line(s) at the end of history
:load <path>             interpret lines in a file
:paste [-raw] [path]     enter paste mode or paste a file
:power                   enable power user mode
:quit                    exit the interpreter
:replay                  reset execution and replay all previous commands
:reset                   reset the repl to its initial state, forgetting all session entries
:save <path>             save replayable session to a file
:sh <command line>       run a shell command (result is implicitly => List[String])
:settings [+|-]<options> +enable/-disable flags, set compiler options
:silent                  disable/enable automatic printing of results
:type [-v] <expr>        display the type of an expression without evaluating it
:kind [-v] <expr>        display the kind of expression's type
:warnings                show the suppressed warnings from the most recent line which had any


3、基本数据类型

    Java支持的基本数据类型,Scala都有对应的支持,不过Scala的数据类型都是对象(比如整数)。

    数值类型:
        整数类型:Byte、Char、Short、Int、Long
        浮点型:Float、Double
    String类型
    Boolean类型

    

    说明:

    除String类型在java.lang包定义,其他的类型都定义在scala包中,Int全名为Scala.Int。Scala运行环境自动会载入包scala和java.lang中定义的数据类型,因此可以直接使用Int,Short,String而无需再引入包或是使用全称。

    由于Scala支持数据类型推断,在定义变量时可以不指明数据类型,而由Scala运行环境自动给出变量的数据类型。

# Scala中的变量可以不指定类型,在赋值时可以根据值推断出其类型,即类型推导
scala> 5;
res0: Int = 5    # Scala会自动转换为变量定义,res0为变量名,Int为变量类型,5为变量值

scala> "hello";
res1: String = hello

scala> (1, 2, 3, 4);
res2: (Int, Int, Int, Int) = (1,2,3,4)

scala> res0;     # 操作res0时,实际上又有一个变量指向它
res3: Int = 5

scala> "hello" * 5;                    # 输出了5个hello,*为方法调用而非运算符
res4: String = hellohellohellohellohello

    Scala的基本数据类型的字面量也支持方法(Java不同,Scala中一切皆对象)。

scala> (-2.7).abs
res13: Double = 2.7

scala> -2.7 abs    // 可以省略点.和括号()
warning: there were 1 feature warning(s); re-run with -feature for details
res14: Double = 2.7

scala> 0 max 5    // 实际调用的是0.max(5)
res15: Int = 5

scala> 4 to 6     // 实际调用的是4.to(6),对于<或者大于>也是作为函数使用
res16: scala.collection.immutable.Range.Inclusive = Range(4, 5, 6)

    这些方法其实是对于基本数据类型的Rich类型的方法

    http://www.scala-lang.org/api/2.11.7/#scala.runtime.RichInt

wKiom1ZzlB_D5m6RAAElvCXBVo4336.jpg

wKiom1Zzk8aAwyl-AACuPro0_Io332.jpg


4、运算符

    Scala中实际并无运算符,所有运算符均为方法的简化表示,比如 1+2 ,实际为 (1).+(2) ,也就是调用RichInt类型的+方法。

scala> val sumMore = (1).+(2)
sumMore: Int = 3

    在Scala中可以将方法作为操作符使用,如String 的IndexOf方法:

scala> var s = "Hello World"
s: String = Hello World

scala> s.indexOf("o")        // 方法调用
res6: Int = 4

scala> s indexOf "o"         // 运算符操作
res7: Int = 4

scala>

    Scala还有前缀运算符和后缀运算符,其方法名都以unary_-开头,如-2.0 实际为 (2.0).unary_-方法。

scala> -2.0
res8: Double = -2.0

scala> (2.0).unary_-
res10: Double = -2.0

    算术运算符 + – × /
    关系和逻辑运算符,包括 >,< ,>=,!等
    逻辑运算支持“短路运算”,比如 op1 || op2 ,当op1=true ,op2无需再计算

scala> def salt() = {println("salt");false}
salt: ()Boolean

scala> def pepper() = {println("pepper");true}
pepper: ()Boolean

scala> pepper() && salt()
pepper
salt
res12: Boolean = false

    位操作符 & | ^ ~

scala> 1 & 2
res14: Int = 0

scala> 1 | 2
res15: Int = 3

scala> 1 ^ 2
res16: Int = 3

scala> ~1
res17: Int = -2

    对象恒等比较

scala> var s1 = "hello";
s1: String = hello

scala> var s2 = "hello";
s2: String = hello

scala> s1 equals s2
res18: Boolean = true

scala> s1.equals(s2)
res19: Boolean = true

scala> s1 == s2
res20: Boolean = true

scala> List(1, 2, 3) == List(1, 2, 3)
res22: Boolean = true

    Scala的==和Java不同,scala 的==只用于比较两个对象的值是否相同。而对于引用类型的比较使用操作符 eq 和 ne。

    操作符的优先级和左右结合性
    Scala 的操作符的优先级和Java基本相同,如果有困惑时,可以使用()改变操作符的优先级。


5、定义变量
    Scala 定义了两种类型的变量 val 和 var 。

    val 类似于Java中的final ,一旦初始化不可重新赋值(称它常量)。

    var类似于一般的非final变量,可以任意重新赋值。

    变量定义:var/val 变量名:变量类型 = 变量值;        // 定义时必须初始化

val msg = "Hello,World";    // 常量
var vmsg = "variable";      // 变量

    定义变量时可以不指定类型,Scala能够根据赋值的内容推算出变量的类型(type inference)。

 val msg2 : String ="Hello again,world";

    也可以在定义变量时指定变量类型。

    注意:Scala中变量不允许只声明而不进行初始化。


6、编写Scala脚本

    printargs.scala文件

var i = 0
while (i < args.length) {
    println(i + "\t" + args(i));
    i += 1;
}

    调用

G:\Hadoop\scala-SDK\source>scala printargs.scala I like scala!
0       I
1       like
2       scala!

    说明:

    Scala不支持++i, i++ 运算符,因此需要使用i+=1 来加一。

    Scala访问数组的语法是使用()而非[]

    printargs.scala文件精简形式:

args.foreach(arg => println(arg))
G:\Hadoop\scala-SDK\source>scala printargs.scala I like scala.
I
like
scala.
/* 或 */
args.foreach(println)
/* 或 */
for (arg <-args)
println(arg)