Reputation: 882
I am writing a gradle task in one of my projects, this task needs to write a kotlin file.
def fileSpec = FileSpec.builder(packageName.toLowerCase(), "ModelClass")
.addType(
TypeSpec.classBuilder("Model")
.primaryConstructor(
FunSpec.constructorBuilder()
.addParameter("name",String.class )
.build()
)
.addProperty(
PropertySpec.builder("name", String.class)
.initializer("name")
.build()
)
.build()
)
.build()
def kotlinFile = new File(dir, "ModelClass.kt")
kotlinFile.withWriter('UTF-8') {
writer ->
fileSpec.writeTo(writer)
}
The task completes without any error but the generated class code lacks kotlin type.
import java.lang.String
public class Model(
public val name: String,
)
The generated class imports String from the java.lang instead of Kotlin Std Lib. My gradle task is written in groovy ( I had to choose groovy because my IDE always complains "code insightful is not available" in the custom gradle.kts file). I guess, we can't generate kotlin file from non-kotlin file or can we?
Upvotes: 0
Views: 109
Reputation: 40218
kotlin.String
doesn't really exist at runtime, it compiles down to java.lang.String
, so when you're trying to access its type using reflection (i.e. String::class
) you get java.lang.String
.
The easiest way around it is to use the STRING
property defined by KotlinPoet. You can also create your own ClassName
if you want: ClassName("kotlin", "String")
.
Upvotes: 0