How to do an instanceof check with Scala(Test)

helpermethod picture helpermethod · Dec 19, 2011 · Viewed 70.3k times · Source

I'm trying to incorporate ScalaTest into my Java project; replacing all JUnit tests with ScalaTests. At one point, I want to check if Guice's Injector injects the correct type. In Java, I have a test like this:

public class InjectorBehaviour {
    @Test
    public void shouldInjectCorrectTypes() {
        Injector injector = Guice.createInjector(new ModuleImpl());
        House house = injector.getInstance(House.class);

        assertTrue(house.door() instanceof WoodenDoor);
        assertTrue(house.window() instanceof BambooWindow);
        assertTrue(house.roof() instanceof SlateRoof);
    }
}

But I have a problem doing the same with ScalaTest:

class InjectorSpec extends Spec {
    describe("An injector") {
        it("should inject the correct types") {
            val injector = Guice.createInjector(new ModuleImpl)
            val house = injector.getInstance(classOf[House])

            assert(house.door instanceof WoodenDoor)
            assert(house.window instanceof BambooWindow)
            assert(house.roof instanceof SlateRoof)
        }
    }
}

It complains that the value instanceof is not a member of Door/Window/Roof. Can't I use instanceof that way in Scala?

Answer

agilesteel picture agilesteel · Dec 19, 2011

Scala is not Java. Scala just does not have the operator instanceof instead it has a parametric method called isInstanceOf[Type].

You might also enjoy watching a ScalaTest Crash Course.