在scala中,方法和函数几乎可以等同(定义、使用、运行机制都一样得),只是函数得使用方式更加得灵活多样,函数像变量一样,既可以作为函数得参数使用,也可以将函数赋值给一个变量,函数得创建不用依赖于类或者对象,而在Java当中,函数得创建则要依赖于类、抽象类或者接口
基本语法
// 函数声明得关键字是defdef 函数名 ([参数名: 参数类型], ...)[[: 返回值类型] =] { 函数体return 返回值 }
函数可以有返回值,也可以没有
def add(a: Int, b: Int): Int = { return a + b; }
def add1(a: Int, b: Int) = { a + b; }
def add2(a: Int, b: Int) { a + b; }
函数参数// 把一个函数赋给一个变量,但是并不执行函数 val f2 = add _
// 指定默认值 def connect(host: String = "localhost", port: Int = 3306, user: String = "root", password: String = "root") = { println("host:" + host + ",port:" + port + ",user:" + user + ",password:" + password) } //host:localhost,port:3306,user:root,password:root connect() //从左到右赋值 // host:127.0.0.1,port:12423,user:root,password:root connect("127.0.0.1",12423) // 带名参数指定覆盖 // host:localhost,port:3306,user:root,password:123456 connect(password = "123456")
// 可变参数 *-parameter must come last // 0到n个参数 def fun(args:Int*): Unit ={ println(args) }






