JsonAdapter<T>.fromJson(string: String): T?

For this piece of code, JsonAdapter<T>.fromJson(string: String): T?, I don’t understand why this is nullable.

If T is a nullable type, then the ? shouldn’t be needed. If it’s not a nullable type, then it seems like it should return T because adapters throw exceptions if deserialization fails.I want to wrap this in my function that takes a nullable string and doesn’t have the nullable return type.

  1. If the string is null and the type isn’t nullable, it should throw an exception.
  2. If it’s null and the type is nullable, it should return null.
  3. Otherwise it should return the T .

fun JsonAdapter.decode(string: String?): T {
if (string == null && /* T is nullable */) return null
return fromJson(string)!!

Is there a way to do this?

Code is ugly as I’m typing on phone and I’m tired, but it gives an idea of how you could do it using an inline function…

inline fun <reified T> JsonAdapter.decode(
    string: String?
): T {
    val value = string?.let{ fromJson(it)} 
    if (value == null && null is T) return null