• 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
    
  • 相关阅读:
    微信小程序 checkbox 组件
    微信小程序 button 组件
    h5视频标签 video
    h5离线缓存
    ECharts插件介绍(图表库)
    rich-text 副文本组件 text文本组件
    progress组件(进度条)
    icon组件
    movable-view组件
    android 双击图片变大,缩放功能
  • 原文地址:https://www.cnblogs.com/studyNotesSL/p/11432907.html
Copyright © 2020-2023  润新知