1、Scala解释器的使用
下载地址:http://www.scala-lang.org/downloads.
Scala的交互式shell就叫做scala。命令提示符输入scala就行(需配置好Java环境变量):
以下是cmd内容:
Microsoft Windows [版本 6.1.7601]
版权所有 (c) 2009 Microsoft Corporation。保留所有权利。
C:\Users\Administrator>scala
Welcome to Scala version 2.10.2 (Java HotSpot(TM) Client VM, Java 1.7.0_79).
Type in expressions to have them evaluated.
Type :help for more information.
scala> 3 + 4
res0: Int = 7
scala> 3 + 5
res1: Int = 8
其中:“res0: Int = 7”表示自动产生的变量res0,计算呢结果为7。
2、变量定义
Scala有两种变量,val和var。
val类似于Java中的final变量,初始化后不能再被赋值。
var则是可以多次赋值的变量。
变量定义及打印输出示例:
scala> val msg = "Hello, world!"
msg: String = Hello, world!
scala> val msg2: java.lang.String = "Hello again. world!"
msg2: String = Hello again. world!
scala> val msg3: String = "Hello ye again, world!"
msg3: String = Hello ye again, world!
scala> println(msg3)
Hello ye again, world!
对msg再次赋值,出错:
scala> msg = "Hi, world!"
<console>:8: error: reassignment to val
msg = "Hi, world!"
^
3、函数定义
Scala函数定义形式:
scala> def max(x: Int, y: Int): Int =
{
if(x > y)
x
else
y
}
//回车输出:
max: (x: Int, y: Int)Int
即定义一个max函数,两个整型参数,函数返回值为Int类型。
测试函数功能:
scala> max(35, 53)
res2: Int = 53
不带参数的函数定义:
scala> def greet() = println("hey, newbie.")
greet: ()Unit
4、编写Scala脚本
把以下代码放在hello.scala文件中:
println("Hello,world, this is a scala script!") 然后运行:
scala>scala hello.scala
//运行结果
Hello,world, this is a scala script!
5、while循环,if判断
while和if示例:
var i = 0
while (i< 10) {
if (i%2 == 0)
print("**")
print(i)
i += 1
}
println()
//结果:
**01**23**45**67**89
i: Int =10
注意:Java的++i和i++在Scala里不起作用,要在Scala里自增,必须写成要么i= i + 1,或者i += 1。