Infix function with wildcard

Hi, why is it that I can declare an infix function like this:

infix fun <T> T.shouldEqual(expected: T) {
    assertEquals(expected, this)
}

and then call it with incompatible types like that:

"mystring" shouldEqual 2

Thank you!

kotlin tries to find common type for T which is Any which is ok for T (no bounds set)
infix is irrelevant you can test it for simple extension method
To test try to specify type explicitly like so

“asd”. shouldEqual(5)

The position is also the same if you don’t have a receiver at all:

fun <T> shouldEqual(actual: T, expected: T) {
    assertEquals(expected, actual)
}

If you then call with:

shouldEqual("mystring", 2) 

the compiler again infers that T is Any, not String or Int.

Ok, how can I set bounds T == T in this case? I only wants to compare String with String etc.

You can effectively do that - at least for the basic types - by specifying that T should implement Comparable<T>:

infix fun <T: Comparable<T>> T.shouldEqual(expected: T) {
    assertEquals(expected, this)
}

The compiler will then determine that T can’t be Any because the latter doesn’t implement Comparable<Any> and so will produce an error.