定义
Scala 2规定函数所有的参数必须有明确的类型,但返回值的类型不是必须的,因为它可以通过上下文推导出来。
scala> def sayHello(name: String) = println("hello," + name)
sayHello: (name: String)Unit
scala> sayHello("scala")
hello,scala
scala> :paste
// Entering paste mode (ctrl-D to finish)
def sayHello(name: String, age: Int) = {
println("hello, " + name, "age is " + age)
// 最后一行代码就是函数的返回值,不需要`return`
age
}
// Exiting paste mode, now interpreting.
sayHello: (name: String, age: Int)Unit
scala> val age = sayHello("scala", 22)
(hello, scala,age is 22)
age: Int = 22
scala> age
res0: Int = 22
原创大约 2 分钟