feat:ChatGPT第 2 课:Scala 函数与方法。
This commit is contained in:
@@ -3,6 +3,7 @@ package practise2.demo
|
||||
object DemoFunction {
|
||||
def main(args: Array[String]): Unit = {
|
||||
hello()
|
||||
|
||||
// 简单的函数
|
||||
def hello(): Unit = {
|
||||
println("Hello Scala")
|
||||
@@ -17,8 +18,9 @@ object DemoFunction {
|
||||
}
|
||||
*/
|
||||
def add(a: Int, b: Int): Int = {
|
||||
a + b // Scala 不需要显式 return
|
||||
a + b // Scala 不需要显式 return
|
||||
}
|
||||
|
||||
val result = add(10, 20)
|
||||
println(result)
|
||||
|
||||
@@ -27,9 +29,10 @@ object DemoFunction {
|
||||
// 最后一句是什么,就返回什么
|
||||
def test(): String = {
|
||||
val a = 10
|
||||
println(a) // 只是打印
|
||||
"Hello" // 才是返回值
|
||||
println(a) // 只是打印
|
||||
"Hello" // 才是返回值
|
||||
}
|
||||
|
||||
val resulTest = test()
|
||||
|
||||
println("========")
|
||||
@@ -38,6 +41,7 @@ object DemoFunction {
|
||||
def hello2(): String = {
|
||||
"Hello"
|
||||
}
|
||||
|
||||
println(hello2())
|
||||
println(hello2) // 也可以省略 ()
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
package practise2.exercises
|
||||
|
||||
/*
|
||||
练习 1:加法函数
|
||||
|
||||
@@ -15,7 +16,8 @@ println(add(10, 20))
|
||||
|
||||
object Exercises1 {
|
||||
def main(args: Array[String]): Unit = {
|
||||
print(add(10,20))
|
||||
print(add(10, 20))
|
||||
}
|
||||
|
||||
def add(a: Int, b: Int): Int = a + b
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
package practise2.exercises
|
||||
|
||||
/*
|
||||
练习 3:判断成年人
|
||||
定义:
|
||||
@@ -15,5 +16,6 @@ object Exercises3 {
|
||||
def main(args: Array[String]): Unit = {
|
||||
print(isAdult(20))
|
||||
}
|
||||
|
||||
def isAdult(age: Int): Boolean = age >= 18
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package practise2.exercises
|
||||
|
||||
|
||||
/*
|
||||
练习 4:成绩评价
|
||||
定义:
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package practise2.exercises
|
||||
|
||||
|
||||
/*
|
||||
练习 5:计算两个数中的较大值
|
||||
定义:
|
||||
|
||||
Reference in New Issue
Block a user