https://kotlinlang.org logo
#serialization
Title
# serialization
c

Császár Ákos

12/12/2023, 11:46 AM
Hi! I am getting the following error:
java.lang.NullPointerException: Parameter specified as non-null is null: method kotlinx.serialization.SerializersKt__SerializersKt.serializer, parameter type
at kotlinx.serialization.SerializersKt__SerializersKt.serializer(Unknown Source:7)
at kotlinx.serialization.SerializersKt.serializer(Unknown Source:1)
The issue is reproducible with this code:
Copy code
inline fun <reified T> decode(body: String) = Json.decodeFromString<T>(body)

@Serializable
class A<T> {
    val value : T? = null
}

@Serializable
class B {
    val type: String? = null
    val name: String? = null
}

class MyClass {
  init {
      fun <T> test(): T? {
          val string = """
              {"value":{"type":"BasicProject","name":"example"}}
      """.trimIndent()
          return decode<A<T>>(string).value
      }
      test<B>()
  }
}
I noticed that if in the test function I replace
T
with the actual type, it works:
Copy code
init {
        fun  test(): B? {
            val string = """
                {"value":{"type":"BasicProject","name":"example"}}
        """.trimIndent()
            return decode<A<B>>(string).value
        }
        test()
    }
Do somebody knows why can't I use
T
as I did, in the first code snippet?
f

franztesca

12/12/2023, 1:56 PM
I guess that, because your
T
generic in
test
is not
reified
, it's hard to tell which deserializer should be used by
decode
. A solution is to make
T
reified:
Copy code
class MyClass {

    init {
        test<B>()
    }

    private inline fun <reified T> test(): T? {
        val string = """
              {"value":{"type":"BasicProject","name":"example"}}
      """.trimIndent()
        return decode<A<T>>(string).value
    }
    
}
But IMHO it's worth opening an issue, the serialization guys will maybe give you a better answer and maybe take action. The error is very obscure
c

Császár Ákos

12/12/2023, 1:58 PM
Thanks! I already created an issue on github java.lang.NullPointerException: Parameter specified as non-null is null: method kotlinx.serialization.SerializersKt__SerializersKt.serializer, parameter type · Issue #2528 · Kotlin/kotlinx.serialization (github.com)