Kotlin函数默认值完全解析

作者: 蓝不蓝编程 | 来源:发表于2019-04-03 13:52 被阅读2次

    简要介绍

    Kotlin函数定义时,支持对参数指定默认值,这样就有效减少Java之前定义重载函数的数量.
    简要对比如下:

    1. Java函数定义,如果sayHelloTo函数中的lastName可以使用默认值,则需要定义如下两个函数.
    public class Person {
        public void sayHelloTo(String firstName,String lastName){
            System.out.println("Hi,"+firstName+" "+lastName);
        }
        public void sayHelloTo(String firstName){
            sayHelloTo(firstName,"noLastName");
        }
    }
    
    1. Kotlin定义如下,只需要一个函数
    class Person {
        fun sayHelloTo(firstName: String, lastName: String = "noLastName") {
            println("Hi,$firstName $lastName")
        }
    }
    

    Kotlin函数默认值详细规则

    1. 可以采用指定全部参数名和不指定参数名的调用方式,推荐采用指定参数名的调用方式(不能指定部分函数参数名,其他的不指定)
      正确样例:
      sayHelloTo("Jerry","Aha")
      sayHelloTo(firstName = "Jerry",lastName = "Aha")
      错误样例:sayHelloTo(firstName = "Jerry","Aha")
    2. 在指定参数名时,所有无默认值参数传入值即可
      样例:sayHelloTo(firstName = "Jerry",lastName = "Aha")
    3. 在不指定参数名时,则需要区分情况:
    • 如果函数定义时,所有具有默认值的参数都在最后,则可以只传入无默认值参数值.
      样例:
      函数定义:fun sayHelloTo(firstName: String, lastName: String = "Aha")
      正确样例:sayHelloTo("Jerry")
    • 如果函数定义时,具有默认值的参数并不都是在最后面,则必须传入所有参数值.
      样例:
      函数定义:fun sayHelloTo(firstName: String, middleName: String = "",lastName: String)
      正确样例:sayHelloTo("Jerry","","Aha")
      错误样例:sayHelloTo("Jerry","Aha")

    Demo代码

    1. Person.kt
    class Person(
        val firstName: String = "Jerry",
        val lastName: String = "Yin"
    ) {
        fun sayHello() {
            System.out.println("Hi,$firstName $lastName")
        }
    
        fun sayHelloTo(firstName: String = "Baby", lastName: String = "Aha") {
            System.out.println("Hi,$firstName $lastName")
        }
    }
    
    1. Person2.kt
    class Person2(
        val firstName: String = "Jerry",
        val lastName: String
    ) {
        fun sayHello() {
            System.out.println("Hi,$firstName $lastName")
        }
    
        fun sayHelloTo(firstName: String = "Baby", lastName: String) {
            System.out.println("Hi,$firstName $lastName")
        }
    }
    
    1. 调用代码:
    Person().sayHello()
    Person("Jerry1").sayHello()
    Person("Jerry2", "Yin2").sayHello()
    Person(firstName = "Jerry3").sayHello()
    Person(lastName = "Yin4").sayHello()
    
    Person().sayHelloTo()
    Person().sayHelloTo("Baby1")
    Person().sayHelloTo("Baby2", "Aha2")
    Person().sayHelloTo(firstName = "Baby3")
    Person().sayHelloTo(lastName = "Aha4")
    
    Person2(lastName = "Yin5").sayHello()
    Person2("Jerry6", "Yin6").sayHello()
    Person2("", "").sayHelloTo(lastName = "Yin8")
    Person2("", "").sayHelloTo("Jerry9", "Yin9")
    

    安卓开发技术分享: https://www.jianshu.com/p/442339952f26
    点击关注专辑,查看最新技术分享
    更多技术总结好文,请关注:「程序园中猿」

    相关文章

      网友评论

        本文标题:Kotlin函数默认值完全解析

        本文链接:https://www.haomeiwen.com/subject/jfzabqtx.html