Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enhancing Type Safety in convertValue #757

Closed
mohamedanees6 opened this issue Jan 10, 2024 · 1 comment
Closed

Enhancing Type Safety in convertValue #757

mohamedanees6 opened this issue Jan 10, 2024 · 1 comment

Comments

@mohamedanees6
Copy link

mohamedanees6 commented Jan 10, 2024

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,

   @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)
    }

Describe alternatives you've considered

No response

Additional context

No response

k163377 added a commit to k163377/jackson-module-kotlin that referenced this issue Jul 6, 2024
@k163377
Copy link
Contributor

k163377 commented Jul 6, 2024

The KotlinModule provides a convertValue extension function.
However, this function has the same problem as #399 .

So, it is closed as a duplicate of #399

@k163377 k163377 closed this as completed Jul 6, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants