mirror of
https://github.com/apple/pkl.git
synced 2026-05-25 16:19:20 +02:00
pkl-config-java: Refine nullness handling in Config and JavaType (#1544)
Motivation:
Config.as() causes nullness warnings when its result is intentionally assigned
to a non-null variable
Changes:
* Introduce Config.asNullable(Class<T>), asNullable(JavaType<T>), and
asNullable(Type) to explicitly opt into nullable values
* Keep the signatures of Config.as(Class<T>) and Config.as(JavaType<T>)
unchanged from 0.31 by adding @NullUnmarked
* This gives users time to migrate from as() to asNullable() where appropriate
* Avoids introducing new spurious warnings
* Change `<T> T Config.as(Type)` to `<T extends @nullable Object> T Config.as(Type)`
* This overload is typically used by reflective code such as
pkl-config-kotlin's Config.to() rather than directly by user code
* Clarify that JavaType<T> represents a non-null top-level type whose type arguments may be nullable
* Restricting <T> to non-null keeps method signatures understandable for humans and tools
* Enables full symmetry between Class<T> and JavaType<T> overloads in Config and JavaType
* Enables future non-null runtime checks in both Config.as() overloads
* Simplify construction of `JavaType`s with nullable type arguments
* Add ofNullable() variants for most factory methods, e.g., JavaType.listOfNullable()
* Overhaul Javadoc of Config and JavaType
Result:
* Clear separation between accessing nullable and non-null values
* Config.as() is used for the common non-null case
* Config.as() can perform non-null runtime checks in a future release (breaking change)
* More ergonomic construction of types with nullable type arguments
* More detailed and consistent documentation
This commit is contained in:
@@ -40,14 +40,15 @@ import org.pkl.config.kotlin.mapper.KotlinConverterFactories
|
||||
* `as(JavaType.listOf(String::class.java))`
|
||||
*/
|
||||
inline fun <reified T> Config.to(): T {
|
||||
val result = `as`<T>(typeOf<T>().javaType)
|
||||
if (result == null && null !is T) {
|
||||
throw ConversionException(
|
||||
if (null is T) {
|
||||
return asNullable(typeOf<T>().javaType)
|
||||
}
|
||||
|
||||
return `as`(typeOf<T>().javaType)
|
||||
?: throw ConversionException(
|
||||
"Expected a non-null value but got `null`. " +
|
||||
"To allow null values, convert to a nullable Kotlin type, for example `String?`."
|
||||
)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
Reference in New Issue
Block a user