Invoke Operator & Operator Overloading in Kotlin

前端 未结 3 579
北海茫月
北海茫月 2020-12-30 23:39

I get to know about the Invoke operator that,

a() is equivalent to a.invoke()

Is there anything more regarding Invoke operator the

3条回答
  •  一个人的身影
    2020-12-31 00:13

    The most way to use a invoke operator is use it as a Factory Method, for example:

    //          v--- call the invoke(String) operator 
    val data1 = Data("1")
    
    //            v--- call the invoke() operator 
    val default = Data()
    
    //          v-- call the constructor
    val data2 = Data(2)
    

    This is because the companion object is a special object in Kotlin. Indeed, the code Data("1") above is translated to the code as below:

    val factory:Data.Companion = Data
    
    //                       v-- the invoke operator is used here
    val data1:Data = factory.invoke("1")
    

    class Data(val value: Int) {
    
        companion object {
            const val DEFAULT =-1
            //           v--- factory method
            operator fun invoke(value: String): Data = Data(value.toInt())
    
            //           v--- overloading invoke operator
            operator fun invoke(): Data = Data(DEFAULT)
        }
    }
    

提交回复
热议问题