scala函数

2019-10-13  本文已影响0人  松松土_0b13

函数定义

默认参数

def sayName(name: String = "hello"): Unit = {
    //toDo
}

命名参数

def speed(distance: Float, time: Float): Floag {
    distance/time
}
println(speed(100, 10))
println(speed(distance = 100, time = 10))
println(speed(time = 10, distance = 100))

可变参数

def sum(numbers:Int*) = {
    var result = 0
    for(num <- numbers) {
        result += num
    }
    result
}
println(sum(1,2,3,4,1))

循环表达式

to | Range | until

# 1 to 10 = 1.to(10)
scala> 1 to 10 <==> 1.to(10)
res0: scala.collection.immutable.Range.Inclusive = Range(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

scala> Range(1,10)
res1: scala.collection.immutable.Range = Range(1, 2, 3, 4, 5, 6, 7, 8, 9)

scala> Range(1,10,2)
res2: scala.collection.immutable.Range = Range(1, 3, 5, 7, 9)

scala> 1 until 10 <==> 1.until(10)
res4: scala.collection.immutable.Range = Range(1, 2, 3, 4, 5, 6, 7, 8, 9)

for循环

for(i <- 1 to 10 if i% 2 == 0){
    println(i)
}
val attr = Array(1,2,3,4,5)
for(i <- attr){
    println(i)
}
attr.foreach(i => println(i))
while () {
}
上一篇下一篇

猜你喜欢

热点阅读