kotlingenericsinheritancehamcrest

Type mismatch for custom generic type in Kotlin


In Kotlin I can write:

fun foo(): List<String> {
    return ArrayList<String>().apply { this.add("1234") }
}

and it works without any issues.

But I tried to do the same with my own generic class:

 fun bar(): Matcher<String> {
     return MyJsonNullableMatcher()
 }

and I see error:

Type mismatch.
Required:
Matcher<String>
Found:
MyJsonNullableMatcher<String>

for me the error looks very unclear

More details:

import org.hamcrest.Matcher
import org.hamcrest.TypeSafeDiagnosingMatcher

class MyJsonNullableMatcher<T> : TypeSafeDiagnosingMatcher<JsonNullable<T>>() {

    override fun describeTo(desc: Description) {
        // doesn't matter
    }

    override fun matchesSafely(actual: JsonNullable<T>, mismatchDescription: Description): Boolean {
         // doesn't matter
        return true
    }
}

TypeSafeDiagnosingMatcher is an descendant of org.hamcrest.Matcher

Could you please clarify ?


Solution

  • MyJsonNullableMatcher<String> is Matcher<JsonNullable<String>>

    but not Matcher<String>

    So this will be correct:

     fun bar(): Matcher<JsonNullable<String>> {
         return MyJsonNullableMatcher()
     }