What is the difference between <reified T> and <reified T: Any> in Kotlin?
The following is a test class.
class SimpleClassTest { private inline fun <reified T> anyObject(): T { return Mockito.anyObject<T>() } lateinit var simpleObject: SimpleClass @Mock lateinit var injectedObject: InjectedClass @Before fun setUp() { MockitoAnnotations.initMocks(this) } @Test fun testSimpleFunction() { simpleObject = SimpleClass(injectedObject) simpleObject.simpleFunction() verify(injectedObject).settingDependentObject(anyObject()) } } But if we move from
private inline fun <reified T> anyObject(): T { return Mockito.anyObject<T>() } to
private inline fun <reified T: Any> anyObject(): T { return Mockito.anyObject<T>() } Failure will be
java.lang.IllegalStateException: Mockito.anyObject<T>() must not be null What is the difference between <reified T> and <reified T: Any> in Kotlin?
UPDATED With the answer that Any is not null, using <reified T: Any> should not return an error, since settingDependentObject(...) declared to receive a non-zero argument. I would expect <reified T> be wrong, but this is the opposite of what I understand.
I got something wrong?
Like the documentation and related answer , the default upper bound is Any? . In other words, the following declarations are equivalent:
inline fun <reified T> anyObject(): T = Mockito.anyObject<T>() inline fun <reified T:Any?> anyObject(): T = Mockito.anyObject<T>() Mockito.anyObject<T>() will return null for T:Any and T:Any? . When a method with a return type of T:Any is called, the null value returned by Mockito does not perform the runtime check inserted by the Kotlin compiler. The error you get is called before settingDependentObject .
When you add a T : Any constraint to a type parameter, you make it effectively non-zero: T is a subtype of Any and Any cannot contain zeros.
Since the function is built-in and has a parameter of type reified, this parameter is replaced by a real non-empty type. And thus, the zero point check is done on the call site, so you get this exception.