加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

def 方法

发布时间:2020-12-16 09:04:28 所属栏目:安全 来源:网络整理
导读:scala def 方法 def 方法名(参数): 返回类型 = {方法体} def fun(name: String): String = { val info = "hello "+ name // 返回值,代码块的最后一行代码的值,不用写return info}// 方法调用println(fun("小李")) hello 小李 方法创建方式 // 无返回值scala

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","c")
arr: Array[String] = Array(a,b,c)

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读