def name="myname"
如果像上面这样定义函数fun,则使用时不能这样使用
val yourname = name()
<console>:15: error: not enough arguments for method apply: (index: Int)Char in class StringOps.
Unspecified value parameter index.
val yourname = name()
只能val yourname = name这样使用。只有函数定义时带有了括号则调用时才能有括号。这样name其实有点像属性。Scala作者建议,如果一个函数在逻辑上表达一种属性的返回值,那么在定义函数时尽量使用不带括号的写法,因为这样看上去更像一个类的属性,而不像一个方法。由于不带括号的函数比带括号的函数在使用上更严格,因此将来要把一个带括号的函数定义改为不带括号的函数定义就比较麻烦——需要先将所有带括号的函数调用,比如name(), 统统改为不带括号的。
还做了一个实验,到现在还不明白原理:
- object WithScope {
- def withScope2(fun: =>String)={
- fun
- }
- def withScope1(fun: (String)=>String)={
- fun
- }
- def fun()={
- println("haha")
- "success"
- }
- def main(args: Array[String]): Unit = {
- withScope2{fun;println(11);"111"}
- }
- }
当我 withScope2{fun;println(11);"111"}时打印如下信息:
haha
11
res6: String = 111