feat:线下课:流程控制、方法和函数
ChatGPT:第 2 课:Scala 函数与方法
This commit is contained in:
@@ -0,0 +1,32 @@
|
||||
package chapter2.demo1
|
||||
|
||||
object DemoMethod {
|
||||
def main(args: Array[String]): Unit = {
|
||||
|
||||
// 函数
|
||||
def sayHello(name: String): Unit = {
|
||||
println(s"hello,${name}")
|
||||
}
|
||||
|
||||
sayHello("zhangsan") // hello
|
||||
// 通过类名去调用方法,等同于java中的静态方法。要求方法定义在object中
|
||||
DemoMethod.sayHello("zhangsan") // hello in object
|
||||
// 创建对象,然后再去调用对象的 sayHello 方法,等同于java中的普通方法。
|
||||
val obj: DemoMethod = new DemoMethod()
|
||||
obj.sayHello("zhangsan") // hello in class
|
||||
|
||||
}
|
||||
|
||||
// 伴生对象中的方法,等同于java的静态方法
|
||||
def sayHello(name: String): Unit = {
|
||||
println(s"hello in object,${name}")
|
||||
}
|
||||
}
|
||||
|
||||
class DemoMethod{
|
||||
|
||||
// 普通方法,不是静态方法
|
||||
def sayHello(name: String): Unit = {
|
||||
println(s"hello in class,${name}")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user