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

Open
mohamedanees6 opened this issue Jan 10, 2024 · 0 comments
Open

Enhancing Type Safety in convertValue #757

mohamedanees6 opened this issue Jan 10, 2024 · 0 comments

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

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

1 participant