我想生成一个非常简单的类,只包含扩展功能,例如以下:
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()
之类的扩展功能?
答案 0 :(得分:1)
val builder = FunSpec.builder("function")
.receiver(SomeClass::class)
.build()
println(builder.build().toString())
会给你:
fun com.my.app.SomeClass.function() {
}