feat:ChatGPT第 2 课:Scala 函数与方法。

This commit is contained in:
2026-09-15 11:35:17 +08:00
parent d2250abaae
commit d31446550d
5 changed files with 14 additions and 4 deletions
@@ -3,6 +3,7 @@ package practise2.demo
object DemoFunction { object DemoFunction {
def main(args: Array[String]): Unit = { def main(args: Array[String]): Unit = {
hello() hello()
// 简单的函数 // 简单的函数
def hello(): Unit = { def hello(): Unit = {
println("Hello Scala") println("Hello Scala")
@@ -19,6 +20,7 @@ object DemoFunction {
def add(a: Int, b: Int): Int = { def add(a: Int, b: Int): Int = {
a + b // Scala 不需要显式 return a + b // Scala 不需要显式 return
} }
val result = add(10, 20) val result = add(10, 20)
println(result) println(result)
@@ -30,6 +32,7 @@ object DemoFunction {
println(a) // 只是打印 println(a) // 只是打印
"Hello" // 才是返回值 "Hello" // 才是返回值
} }
val resulTest = test() val resulTest = test()
println("========") println("========")
@@ -38,6 +41,7 @@ object DemoFunction {
def hello2(): String = { def hello2(): String = {
"Hello" "Hello"
} }
println(hello2()) println(hello2())
println(hello2) // 也可以省略 () println(hello2) // 也可以省略 ()
@@ -1,4 +1,5 @@
package practise2.exercises package practise2.exercises
/* /*
练习 1:加法函数 练习 1:加法函数
@@ -15,7 +16,8 @@ println(add(10, 20))
object Exercises1 { object Exercises1 {
def main(args: Array[String]): Unit = { def main(args: Array[String]): Unit = {
print(add(10,20)) print(add(10, 20))
} }
def add(a: Int, b: Int): Int = a + b def add(a: Int, b: Int): Int = a + b
} }
@@ -1,4 +1,5 @@
package practise2.exercises package practise2.exercises
/* /*
练习 3:判断成年人 练习 3:判断成年人
定义: 定义:
@@ -15,5 +16,6 @@ object Exercises3 {
def main(args: Array[String]): Unit = { def main(args: Array[String]): Unit = {
print(isAdult(20)) print(isAdult(20))
} }
def isAdult(age: Int): Boolean = age >= 18 def isAdult(age: Int): Boolean = age >= 18
} }
@@ -1,5 +1,6 @@
package practise2.exercises package practise2.exercises
/* /*
练习 4:成绩评价 练习 4:成绩评价
定义: 定义:
@@ -1,5 +1,6 @@
package practise2.exercises package practise2.exercises
/* /*
练习 5:计算两个数中的较大值 练习 5:计算两个数中的较大值
定义: 定义: