Not satisfied: inferred type T? is not subtype of Any

QuokMoon picture QuokMoon · Feb 22, 2018 · Viewed 7.2k times · Source

To map the result I have implemented sealed generic class :

public sealed class ResultMapper<out T : Any> {
    public class Ok<out T : Any>(public val value: T,
                            override val response: Response) : Result<T>(), ResponseResult {
        override fun toString(): String = "Result.Ok{value=$value, response=$response}"
    }
}

   public interface ResponseResult {
     val response: Response
   } 

Now I suppose to this class should work as expected below behaviour:

 ResultMapper.Ok(body,raw)

private class Body<T>() {
  onResponse(response: Response, raw: Raw) {
   ResultMapper.Ok(response.body(),response.raw()) --> It returned an exception
  }
}

Constructor Ok is not satisfied: inferred type T? is not subtype of Any

Answer

s1m0nw1 picture s1m0nw1 · Feb 22, 2018

The class Body has a generic type parameter T without any bounds, i.e. it’s like defining T: Any? whereas Ok’s type parameter is confined to be T: Any. You should adjust Body to not allow nullable types either:

class Body<T: Any>

Alternatively, remove the upper bound in the other classes.