scala(6)Learn CH8 Programming in Scala from others

本文深入探讨Scala编程中的闭包、多参数函数和命名参数的使用技巧,通过实例展示了如何定义和应用这些高级特性来简化代码逻辑。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

scala(6)Learn CH8 Programming in Scala from others
Function can be used as an parameter, because function is also an object. It can be changed during processing.

package com.sillycat.easyscala.lesson6

object TestMutableFunction {
def main(args: Array[String]): Unit = {
//defined a function x+1
var increase = (x: Int) => x + 1
println(increase(10))

//redefined the function to x+5
increase = (x: Int) => x + 5
println(increase(10))

val l = List(1, 3, 5, 7, 9, 11)
println(l)

val l2 = l.filter((x: Int) => x > 2)
println(l2)

val l3 = l.filter(x => x > 3)
println(l3)

val l4 = l.filter(_ > 5)
println(l4)

val f = (_: Int) + (_: Double)
val v5 = f(3, 5)
println(v5)

//sum with multiple parameters
val asum = sum _
val v6 = asum(1, 2, 3)
println(v6)

val psum = sum(3, _: Int, 5)
val v7 = psum(7)
println(v7)
}

def sum(a: Int, b: Int, c: Int): Int = {
a + b + c
}
}

Some kinds of Closure like this:
package com.sillycat.easyscala.lesson6

object TestClosure {

def main(args: Array[String]): Unit = {
var more = 0
//in function, we can use the variable defined outside the function
val mf = (_: Int) + more
println(mf(10))

//the variable can be changed
more = 10
println(mf(10))

val l = List(1, 3, 4, 5, 9)
var sum = 0
l.foreach(sum += _)
println(sum)
}

}

Our parameters for functions can be multiple and changeable.
package com.sillycat.easyscala.lesson6

object RepeatedParams {
def main(args: Array[String]): Unit = {
echo()
echo("Hello")
echo("Hello", "World")

val a = Array("Hello", "world")
// take all the elements in a to parameters pass to echo
echo(a: _*)
}

// The parameters are multiple and changeable
def echo(args: String*): Unit = {
for (arg <- args)
println(arg)
}
}

Sometimes, it is useful to give names to the parameters in functions. We do not need to care about the order of the parameters if we provide the parameter names.
package com.sillycat.easyscala.lesson6

object NamedArgument {
def main(args: Array[String]): Unit = {
val a = speed(distance = 100, time = 9)
println(a) //11.1111111111

//give the parameter names during calling the functions
val b = speed(time = 10, distance = 101)
println(b) //10.1

println(speed(1,2)) //0.5
}

//define a name for the function
def speed(distance: Double, time: Double) = distance / time
}


References:
http://snowriver.org/blog/2011/03/20/programming-in-scala-ch8-function-and-closer/
http://snowriver.org/blog/tag/scala/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值