1.无参方法,加不加都可以执行。因为都可以执行,所以遇到不想它执行时,比如函数作为参数传递时,可以加上下划线 _
object FuncProgrammingDemo { def main(args: Array[String]): Unit = { myPrint //hello myPrint() //hello } def myPrint(): Unit ={ println("hello") } }
2.隐式匹配时,加了会报错,不加能成功执行
object FuncProgrammingDemo { implicit val v = "scala" def main(args: Array[String]): Unit = { myPrint //scala } def myPrint(implicit str:String): Unit ={ println(str) } }
3.函数赋值给变量后,加了才执行,不加不执行。
object FuncProgrammingDemo { def main(args: Array[String]): Unit = { val f = myPrint _ //f没有执行 f f() //hello } def myPrint(): Unit ={ println("hello") } }
4.在控制抽象函数里。在test方法中,空参函数f的小括号去掉后,在test里调用不能加小括号,加了会报错。
object ScalaDemo { def main(args: Array[String]): Unit = { //传递参数函数f时,直接传递代码块 test{ println("hello") println("scala") } } //去掉入参的小括号 def test(f: => Unit) = { //调用时也去掉小括号 f } }