0

我想生成一个非常简单的类,它只包含扩展函数,如下所示:

import com.my.app.SomeClass

fun SomeClass.function() {
}

我尝试什么:

val packageName = ...
val annotatedClassName = annotatedElement.simpleName
val fileName = "${annotatedClassName}_KotArgsExtensions"

val extensionBuilder = FileSpec.builder(packageName, fileName)

val funSpecBuilder= FunSpec.builder("${SomeClass::class.java.simpleName}.function").build()
extensionBuilder.addImport(SomeClass::class.java.`package`.name, SomeClass::class.java.simpleName)

extensionBuilder.addFunction(funSpecBuilder)

我得到什么:

import com.my.app.SomeClass

fun `SomeClass.function`() {
}

问题

我怎样才能正确地创建一个扩展函数,比如fun SomeClass.function()

4

1 回答 1

5

使用FunSpec.Builder.receiver()

val builder = FunSpec.builder("function")
    .receiver(SomeClass::class)
    .build()
println(builder.build().toString())

会给你:

fun com.my.app.SomeClass.function() {
}
于 2019-08-13T20:02:46.213 回答