jocarreira / hamcrest

Automatically exported from code.google.com/p/hamcrest
0 stars 0 forks source link

Compiler error when using assertThat and polymorphism (still present after fix of issue #31) #32

Closed GoogleCodeExporter closed 8 years ago

GoogleCodeExporter commented 8 years ago
Hi Nat,

Re issue#31 - unfortunately the change you committed didn't fix the
problem. I must say, my first reaction was that "Matcher<? super T>" would
fix the problem but it doesn't. It would be right if "T" meant "the type
expected by the method 'matches'", but the matcher defines "boolean
matches(Object item)" so T must mean something else.

I think the right answer might be:
    public static <T> void assertThat(T actual, Matcher<?> matcher)

Also, I realised my previous example had a custom class in it, so here's an
example that uses standard Java classes:

     public void testCanBeUsedPolymorphically() {
        Double doub = new Double(0);
        Number doubleAsNumber = doub;

        assertThat2(doubleAsNumber, equalTo(doub));          // ERROR!
        assertThat2(doub,           equalTo(doubleAsNumber));
    }

Original issue reported on code.google.com by i.am.pau...@googlemail.com on 7 Mar 2008 at 6:55

GoogleCodeExporter commented 8 years ago
You want the static type system to magically know the dynamic types of the 
objects
being compared.  It can't.

Maybe the issue is really with the definition of equalTo.  The equals method is 
not
generic -- it compares values of type Object -- so equalTo should perhaps 
return a
Matcher<Object> not a Matcher<T>.

Original comment by nat.pr...@gmail.com on 6 Jul 2008 at 11:50

GoogleCodeExporter commented 8 years ago
Thinking about this, this is *NOT* a compile error.  The compiler is telling 
you that
you cannot compare Double objects with just any kind of Number.  This is 
correct.

Original comment by nat.pr...@gmail.com on 24 Oct 2008 at 12:33