Search code examples
androidkotlinpoetksp

Ticks within the package name


I work with KSP and retrieve the package name like this:

val packageName = data.resolver.getKotlinClassByName(className.canonicalName).packageName.asString()

When then trying to write the file it works fine

FileSpec.builder(packageName, "name").build()

Except when data is inside the package name, it renders as this in the generated file

package com.otherpackage.'data' // That's actually not ' but `

I logged the packageName as well as the fileSpec.packageName variables and they render "com.otherpackage.data" as expected but it's when the generation is done, it renders with the ticks. Could you tell if this is normal and if so how I could workaround that? It's not possible to import files "automatically" with the \`data\` in their package name in Android Studio (shrug)Thanks in advance


Solution

  • This is normal: KotlinPoet errs on the side of safety and automatically wraps all reserved keywords with backticks, including soft and modifier keywords, even though they can technically be used as identifiers in most cases. The compiler treats package com.otherpackage.data and package com.otherpackage.'data' (with backticks, not single quotes) as the same expression, so backticks shouldn't cause compilation errors. If you'd like to get rid of backticks for code style reasons, you can post-process KotlinPoet's output to remove them.