On calling mapper.convertValue(null, String::class.java), can we return a nullable type T instead of T through a wrapper? This will enhance type safety in Kotlin.
Describe the solution you'd like
Below code results in NPE,
@Test
fun test() {
val kotlinModule = KotlinModule.Builder()
.enable(KotlinFeature.StrictNullChecks)
.build()
val mapper = JsonMapper.builder()
.addModule(kotlinModule)
.build()
val convertValue = mapper.convertValue(null, String::class.java)
print(convertValue.toString())
}
I've made this workaround, can we think of creating a wrapper function that can provide type-safety? Its safer to assume objects coming from Java to be nullable always, rather than throwing NPE.
@Test
fun testNullSafe() {
val convertValue: String? = demoFunction("demo", String::class.java)
Assertions.assertEquals(4, convertValue?.length ?: 0)
val convertValueNull: String? = demoFunction(null, String::class.java)
Assertions.assertEquals(0, convertValueNull?.length ?: 0)
}
private fun <T> demoFunction(input: String?, clzz: Class<T>): T? {
val kotlinModule = KotlinModule.Builder()
.enable(KotlinFeature.StrictNullChecks)
.build()
val mapper = JsonMapper.builder()
.addModule(kotlinModule)
.build()
return mapper.convertValue(input, clzz)
}
Use case
On calling
mapper.convertValue(null, String::class.java)
, can we return a nullable type T instead of T through a wrapper? This will enhance type safety in Kotlin.Describe the solution you'd like
Below code results in NPE,
I've made this workaround, can we think of creating a wrapper function that can provide type-safety? Its safer to assume objects coming from Java to be nullable always, rather than throwing NPE.
Describe alternatives you've considered
No response
Additional context
No response