创建扩展功能(名称中带有。的功能)

时间:2019-08-13 10:57:02

标签: kotlinpoet

我想生成一个非常简单的类,只包含扩展功能,例如以下:

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()之类的扩展功能?

1 个答案:

答案 0 :(得分:1)

使用FunSpec.Builder.receiver()

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

会给你:

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