def 方法

scala def 方法

def 方法名(参数): 返回类型 = {方法体}

def fun(name: String): String = {
    val info = "hello "+ name
    
    // 返回值,代码块的最后一行代码的值,不用写return
    info
}

// 方法调用
println(fun("小李"))
hello 小李

方法创建方式

// 无返回值
scala> def fun(): Unit ={println("---")}
fun: ()Unit

scala> fun()
---

// 自动推断返回值类型
scala> def fun() = {print("!!!")}
fun: ()Unit

// 无参数时可以不写括号,但调用时也不能写括号
scala> def fun = print("!!!")
fun: Unit

scala> fun
!!!

// 没有返回值的时候 "=" 可以省略
scala> def fun {print("!!!")}
fun: Unit

scala> fun
!!!

默认参数

// 默认参数,不能省略变量的类型
scala> def fun(name: String = "aabb") = print(name+" !!!")
fun: (name: String)Unit

scala> fun()
aabb !!!

scala> fun(name = "abc")
abc !!!

可变长参数

// 可变长参数,内部是Array[T]的数组
scala> def fun(name: String*) = for(e <- name) println("hello "+e)
fun: (name: String*)Unit

scala> fun("a","b","c")
hello a
hello b
hello c

scala> val arr = Array("a","b","c")
arr: Array[String] = Array(a, b, c)

// 将arr里面的每一个数据取出来放进去
scala> fun(arr:_*)
hello a
hello b
hello c

猜你喜欢

转载自www.cnblogs.com/studyNotesSL/p/11432907.html
def
今日推荐