google / google/ksp

Default values for annotation properties not found when using KSP2 with Kotlin Multiplatform

Open
#2,491 5 comments 0 reactions 1 assignee Claimed by @jaschdoc View on GitHub
bug core P3
Dominant language
Kotlin
Stars
3.5k
Forks
415
Avg merge
1d 2h
Merged PRs (30d)
53

Description

I'm writing a KSP annotation parser for this annotation :
```kotlin
@Target(AnnotationTarget.CLASS)
@Retention(AnnotationRetention.SOURCE)
annotation class DataObject(
val dataSizeFormat: DataSizeFormat = DataSizeFormat.INT,
val order: Order = Order.BIG_ENDIAN
)
```

The processor is declared for the common code of a Kotlin Multiplatform project like this :
```kotlin
dependencies {
add("kspCommonMainMetadata", project(":my-processor"))
}
```

In the project, sometimes the annotation use the default value. In that case, in the processor, an exception happens. For example with this code :
```kotlin
fun processClass(clazz: KSClassDeclaration) {
val dataObjectAnnotation = clazz.getAnnotationsByType(DataObject::class).first()
val dataSize = dataObjectAnnotation.dataSizeFormat
...
}
```

This exception occurs on the last line, where I try to access dataSizeFormat : `java.util.NoSuchElementException: Collection contains no element matching the predicate.`

If the value of the annotation property is overridden, then there is no error. Also it works fine when I use the processor on a JVM build, by replacing the dependency above with :
```kotlin
dependencies {
add("kspJvm", project(":my-processor"))
}
```

The workaround I found for now is to use a try/catch block and reflection to retrieve the default value, but I don't know if there is a better solution or if this problem could be solved in KSP.

KSP version used is 2.1.21-2.0.1

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.