跳到内容

可调用引用

对构造函数、函数和属性的可调用引用可以通过以下方式发出:

  • ClassName.constructorReference() 用于构造函数
  • MemberName.reference() 用于函数和属性

例如,

val helloClass = ClassName("com.example.hello", "Hello")
val worldFunction: MemberName = helloClass.member("world")
val byeProperty: MemberName = helloClass.nestedClass("World").member("bye")

val factoriesFun = FunSpec.builder("factories")
  .addStatement("val hello = %L", helloClass.constructorReference())
  .addStatement("val world = %L", worldFunction.reference())
  .addStatement("val bye = %L", byeProperty.reference())
  .build()

FileSpec.builder("com.example", "HelloWorld")
  .addFunction(factoriesFun)
  .build()

会生成

package com.example

import com.example.hello.Hello

fun factories() {
  val hello = ::Hello
  val world = Hello::world
  val bye = Hello.World::bye
}

成员名称一样,名称冲突的顶层类和成员可能需要使用别名导入。