kotlin className.() 类名点花括号 T.() 这种是什么意思?

阅读别人的代码,经常看到这样的T.() 这样的写法,一时没有明白是什么意思,现在知道了。 className.() 的意思,就是省略了以 className 为类型的参数,代表这个有一个 className 类型的参数,没有省略的时候,写法是这样的

jsfun 复制代码
表示的是 
fun xxx(obj:ClassName){}
或者 Lamabda
{
   obj:ClassName->
   xxx
}

下面我们用代码来测试一下,便于更好的理解

kotlin 复制代码
class CommonTestTwo {
    fun testOne(){
        println("testOne is called")
    }
}
/* ClassName.()在高阶函数中出现,作为高阶函数的一个参数,表示: 一个以 ClassName 对象作为参数的函数或者Lamabda
* fun ClassName.()
* 表示的是
* fun xxx(obj:ClassName){}
* 或者 Lamabda
* {
*    obj:ClassName->
*    xxx
* }
* */
fun testTwo(s:CommonTestTwo):Unit{
    println("testTwo s = $s")
}
//addFunction是个扩展函数,CommonTestTwo.() 表示CommonTestTwo作为参数类型
fun String.addFunction(action:CommonTestTwo.()->Unit){
    val commonTestTwo = CommonTestTwo()
    println("addFunction commonTestTwo = $commonTestTwo")
    commonTestTwo.action()
}

/*fun String.addFunction(action:CommonTestTwo.()->Unit) 这个写法,就相当于
  fun String.addFunction0(action:(obj:CommonTestTwo)->Unit){}
  action 是一个类型为(obj:CommonTestTwo)->Unit的函数参数
* */

//扩展函数2
fun String.addFuntion2(action:(CommonTestTwo)->Unit){
    val commonTestTwo = CommonTestTwo()
    println("addFunction2 commonTestTwo = $commonTestTwo")
    action(commonTestTwo)
}
fun main(){
    val testStr = ""
    //第一种
    val f1 = {
        a:CommonTestTwo ->
        println("f1 a = $a")
    }
    testStr.addFunction(f1)
    testStr.addFuntion2(f1)
    //第二种: 高阶函数直接传函数作为参数是用双冒号::
    testStr.addFunction(::testTwo)
    testStr.addFuntion2(::testTwo)
    //第三种
    testStr.addFunction {  }
    testStr.addFuntion2 {  }
}

输出的结果如下: addFunction commonTestTwo = commontest.CommonTestTwo@12edcd21 f1 a = commontest.CommonTestTwo@12edcd21 addFunction2 commonTestTwo = commontest.CommonTestTwo@27973e9b f1 a = commontest.CommonTestTwo@27973e9b addFunction commonTestTwo = commontest.CommonTestTwo@5e9f23b4 testTwo s = commontest.CommonTestTwo@5e9f23b4 addFunction2 commonTestTwo = commontest.CommonTestTwo@378fd1ac testTwo s = commontest.CommonTestTwo@378fd1ac addFunction commonTestTwo = commontest.CommonTestTwo@6e2c634b addFunction2 commonTestTwo = commontest.CommonTestTwo@7e6cbb7a

如上,如有不同理解,欢迎留言交流评论,请文明评论,谢谢

相关推荐
日光明媚8 小时前
一步生成视频!One-Forcing:DMD + 零成本 GAN,训练 200 步超越多步 SOTA
android·开发语言·kotlin
plainGeekDev10 小时前
Android运行时面试题:ART和JVM的区别都搞不清,别写精通了
jvm·面试·kotlin
Refrain_zc2 天前
Android Kotlin + MVVM:基于 LiveData 的段落列表音频播放与 AB 复读实现
kotlin
赏金术士2 天前
企业级 Jetpack Compose 项目(入门版)最佳结构
android·kotlin·compose
我是唐青枫2 天前
Kotlin Lambda 表达式详解:从基础语法到实战封装
开发语言·kotlin
Kapaseker2 天前
Kotlin 的扩展没有你看上去的那么简单
android·kotlin
黄林晴2 天前
告别 KMP 选型地狱!klibs.io 上线,全平台库一键筛选太省心
android·kotlin
吕氏春秋i2 天前
android kotlin Compose 蓝牙库推荐
android·gitee·kotlin
鹏晨互联2 天前
《Kotlin高阶函数完全指南:从入门到精通的15个核心函数》
android·开发语言·kotlin
android_cai_niao2 天前
快速删除集合中的元素
kotlin·removeif