Scala函数定义:
def 函数名(参数列表,...):返回结果类型={},下面给出一个max函数
def max(a: Int,b: Int):Int ={
if(a > b)
a
else
b
}
var maxValue = max(6,10)
println("max(6, 10) the max maxValue is :" + maxValue )
println("max(6, 10) the max is :" + max(6,10) )
返回结果是较大的值
max(6, 10) the max maxValue is :10
max(6, 10) the max is :10
1,有时函数必须制定返回结果类型,如函数时递归,就必须明确制定返回结果类型
2,在max这里例子中及时不写返回结果,编译器也能推断,如实这个函数就 编程如下的样子,作用功能都没有变化
def max2(a: Int,b: Int)={
if(a > b)
a
else
b
}
3,如果函数仅 一个语句,连花括号都可以不写。如是max函数就成了这样,作用功能仍然没有变化def max3(a: Int,b: Int)=if(a > b) a else b
Scala流程控制:
def max3(a: Int,b: Int)=if(a > b) a else b
scala中的if else和java中的基本一致,如下代码:
object ControlStatementIfElse {
def main(args: Array[String]) {
val k=5
if (k>10) {
println("k is more than 10")
} else if(k<0) {
println("k is less than 0")
} else {
println("k is between 1 and 10")
}
}
}
这里的if else基本和java/c是一致的。我们继续看下while语句
object ControlStatementWhile {
def main(args:Array[String]) {
var i=0;
var sum=0
while (i<10) {
sum += i
i += 1
}
println(sum)
}
}
while语句的语法也很简单,需要注意在scala中数字类型没有++ --方法
下面看一下scala中的for循环语句
import scala.util.control.Breaks._
import scala.util.Random
object ControlStatementBreak {
def main(args:Array[String]) {
breakable {
while (true) {
val r = new Random()
val i = r.nextInt(10)
println("i==" + i)
if (i == 5) {
break
}
}
}
}
}
在这段代码中首先我们import了scala.util.control.Breaks._,这样我们就可以使用breakable,和break语句了。
我们在while语句的外面用breakable语句块包围了,然后在需要break的地方调用break方法,这里的break不是关键字,而是一个scala的方法,这个方法会抛出异常,从而中断循环。
下面我们看下scala中break实现的方式,首先看breakable,其实它也是一个函数。
其代码如下:
def breakable(op: => Unit) {
try {
op
} catch {
case ex: BreakControl =>
if (ex ne breakException) throw ex
}
}
breakable接受一个函数做参数,他会在这个要执行的函数op旁添加try catch,如果catch住的异常是breakException,那么不做处理,如果不是则抛出异常。
我们再看下break函数的实现:
def break(): Nothing = { throw breakException }
这个函数返回值是Nothing,在它的方法体内直接抛出了breakException