创建扩展函数(名称中带有 . 的函数)

Create extension function (function with . in name)

我想生成一个非常简单的 class,它只包含扩展函数,例如以下:

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() 这样的扩展函数?

使用FunSpec.Builder.receiver():

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

会给你:

fun com.my.app.SomeClass.function() {
}