第2章——体验Scala

令人惊喜的是,无论是创建一个简短的脚本还是一个完整的企业级应用,都可以轻松地 用 Scala 代码实现并运行。你可以使用任何 IDE,也可以只使用轻量级的编辑器。

2.1 使用 REPL

Welcome to Scala 2.12.6 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_172).
Type in expressions for evaluation. Or try :help.

scala>
Full source at GitHub
scala> val number = 6
number: Int = 6
Full source at GitHub
scala> number = 7
<console>:11: error: reassignment to val
       number = 7
              ^
Full source at GitHub
scala> val number = 7
number: Int = 7
Full source at GitHub
scala> val list = List(1, 2, 3)
list: List[Int] = List(1, 2, 3)
Full source at GitHub
scala> def isPalindrome(str: String) =
     |   str == str.reverse
isPalindrome: (str: String)Boolean

scala> isPalindrome("mom")
res0: Boolean = true

scala> isPalindrome("dude")
res1: Boolean = false

scala> :quit
Full source at GitHub

2.2 命令行上的 Scala

println("Hello World, Welcome to Scala")
Full source at GitHub

运行结果

>scala HelloWorld.scala
Hello World, Welcome to Scala
Full source at GitHub

2.3 以独立脚本方式运行 Scala 代码

#!/usr/bin/env scala

println("Hello " + args(0))
Full source at GitHub

运行命令

hello.sh Buddy
Full source at GitHub

运行结果

Hello Buddy
Full source at GitHub
echo off

cls
call scala %1
pause
Full source at GitHub

2.4 编译 Scala

FirstStep/Sample.scala

object Sample extends App {
  println("Hello Scala")
}
Full source at GitHub

运行结果

> scalac Sample.scala
> scala Sample
Hello Scala
> java -classpath /opt/scala/current/lib/scala-library.jar:. Sample
Hello Scala
Full source at GitHub