Scala基础
来源:互联网 发布:linux 下载速度很慢 编辑:程序博客网 时间:2024/06/14 14:58
原文:https://my.oschina.net/joymufeng/blog/652409
1. 介绍
传值参数在函数调用之前表达式会被求值,例如Int,Long等数值参数类型;传名参数在函数调用前表达式不会被求值,而是会被包裹成一个匿名函数作为函数参数传递下去,例如参数类型为无参函数的参数就是传名参数。下文将举例说明这两者的区别。
2. 简单类型的传递示例
2.1 传值参数(by-value parameter)示例
在下面的示例中,编译器检测到strToInt接受一个传值参数,所以先对传入的参数表达式{println("eval parameter expression"); "123"}
,然后再讲求值结果传递给strToInt。
object Test {
def strToInt(s: String) = {
println("call strToInt")
s.toInt
}
def main(args: Array[String]) {
strToInt({println("eval parameter expression"); "123"})
}
}
//输出:
eval parameter expression
call strToInt
2.2. 传名参数(by-name parameter)示例
在strToInt
函数声明中添加一个=>
,参数s的类型就变成了无参函数,类型为:() => String
,按照Scala针对无参函数的简化规则,此处省略了()
。因为参数s的类型是无参函数,所以此处是按名传递。
def strToInt(s: => String) = {
println("call strToInt")
s.toInt
}
def main(args: Array[String]) {
strToInt({println("eval parameter expression"); "123"})
}
}
//输出:
call strToInt
eval parameter expression
从上面的输出可以看出,参数表达式在strToInt
函数调用之后才被求值。其实此处编译器自动将参数表达式{println("eval parameter expression"); "123"}
转换成匿名的无参函数,并传递给s
。
3. 复杂类型的传递示例
3.1 传值参数(by-value parameter)示例
invode函数的参数f的类型为柯里化函数String => Int => Long
, 此处为按值传递。
def invode(f: String => Int => Long) = {
println("call invoke")
f("1")(2)
}
def curry(s: String)(i: Int): Long = {
s.toLong + i.toLong
}
def main(args: Array[String]) {
invode{println("eval parameter expression");curry}
}
}
//输出:
eval parameter expression
call invoke
3.2 传名参数(by-name parameter)示例
invode函数的参数f的类型为一个无参函数,该无参函数的返回类型为柯里化函数String => Int => Long
, 因为参数f的类型是无参函数,所以此处是按名传递。
def invode(f: => String => Int => Long) = {
println("call invoke")
f("1")(2)
}
def curry(s: String)(i: Int): Long = {
s.toLong + i.toLong
}
def main(args: Array[String]) {
invode{println("eval parameter expression");curry}
}
}
//输出:
call invoke
eval parameter expression
4. 小结
如果参数类型是无参函数,则按名传递,否则按值传递。注意,如果参数类型是函数类型,但不是无参函数,还是按值传递,例如:
object Test {def strToInt(s: (String) => Int) = {
println("call strToInt")
s("123")
}
def main(args: Array[String]) {
strToInt({println("eval parameter expression"); (s: String) => s.toInt})
}
}
//输出:
eval parameter expression
call strToInt
- Scala基础
- Scala 基础
- Scala 基础
- Scala 基础
- Scala基础
- scala 基础
- scala 基础
- Scala基础
- Scala基础
- Scala基础
- Scala基础
- Scala 基础
- Scala基础
- scala-基础
- Scala基础
- Scala基础
- scala基础
- Scala 基础
- 【精通hibernate】(4)hibernate事务管理以及并发问题处理
- Codeforces 712D Memory And Scores 前缀和+DP
- 洛谷 P1091 合唱队形
- error C2143: syntax error : missing ';' before
- Houdini学习 —— 基于节点的过程化建模初探及思考
- Scala基础
- 数据库学习中使用的表
- 算法第4版(Java语言描述)课后习题答案
- Android问题集锦之五十二:unsupported reloc 43
- 判断组成回文的字符串序列
- vim键盘操作(中班)
- redis小本本(二)
- 接口安全之短信验证(防恶意被刷)
- WindowManager中悬浮窗的返回键事件处理