1 class Student { 2 3 val mySayHello1: String => Unit = sayHello 4 val mySayHello2: (String, Int) => Unit = sayHello 5 val myTalkTo = talkTo _ 6 val myJumpStart: () => String = jumpStart 7 8 def sayHello(name: String) = { 9 println("Hello 1, " + name) 10 } 11 12 def sayHello(name: String, age: Int) = { 13 println("Hello 2, " + name + "," + age) 14 } 15 16 def talkTo(name: String, age: Int): Unit = { 17 println("Talk to , " + name + "," + age) 18 } 19 20 def jumpStart(): String = { 21 "Start to Jump" 22 } 23 24 } 25 26 object FunctionDemo { 27 28 def main(args: Array[String]): Unit = { 29 val s = new Student() 30 //操作标记法调用方法 31 s sayHello "bill" 32 //操作标记法调用方法 33 s sayHello ("bill", 20) 34 //函数类型赋值 35 s.sayHello("bill") 36 s.sayHello("bill", 20) 37 //用通配符为函数赋值 38 s.myTalkTo("bill", 10) 39 //无输入参数函数赋值 40 println(s.myJumpStart()) 41 42 } 43 }
时间: 2024-10-08 18:16:50