多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
函数定义 ```scala def max(x: Int, y: Int): Int = { if (x > y) x else y } ``` ```scala def 方法名(参数名: 参数类型): 返回值类型 = { // 方法体 // 最后一行为返回值,不需要 return } ``` 调用无参方法可省略括号 ```scala object Person { def main(args: Array[String]): Unit = { sayNameAgain } def sayNameAgain(): Unit ={ println("Apollo") } } ``` 默认参数 ```scala object Person { def main(args: Array[String]): Unit = { sayName() sayName("Apollo") } def sayName(name: String = "Default_Name"): Unit = { println(name) } } ``` 命名参数 ```scala object Person { def main(args: Array[String]): Unit = { println(getSpeed(10, 2)) println(getSpeed(distance = 10, time = 2)) println(getSpeed(time = 2, distance = 10)) } def getSpeed(distance: Float, time: Float): Float = { distance / time } } ``` 可变参数 ```scala object Person { def main(args: Array[String]): Unit = { println(sum(10, 2)) println(sumPlus(1, 2, 3, 4, 5, 6, 7, 8)) } def sum(a: Int, b: Int): Int = { a + b } def sumPlus(numbers: Int*): Int = { var result = 0; for (number <- numbers) { result += number } result } } ``` 条件表达式 ```scala object Person { def main(args: Array[String]): Unit = { val x = 100 val res = if (x > 10)//可以赋值 true else false println(res) } } ``` 循环表达式 ```scala object Person { def main(args: Array[String]): Unit = { println(1 to 10) println(1.to(10)) } } ``` ``` Range(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) Range(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) ``` ```scala object Person { def main(args: Array[String]): Unit = { println(1 until 10) println(1.until(10)) } } ``` ``` Range(1, 2, 3, 4, 5, 6, 7, 8, 9) Range(1, 2, 3, 4, 5, 6, 7, 8, 9) ``` ```scala for (i <- 1 to 10) { println(i) } for (i <- 1 to 10 if i % 2 == 0) { println(i) } ``` ```scala val team = Array("Apollo", "Paul", "Tom", "Amy") for (person <- team){ println(person) } ``` ```scala val team = Array("Apollo", "Paul", "Tom", "Amy") team.foreach(person => println(person)) ```