scala中有奇怪的isInstanceOf行为

时间:2016-02-20 20:32:22

标签: scala scalatest

使用ScalaTest/FlatSpec库我正在使用函数状态测试随机数生成器返回值的类型:

it should "return (\"{someRandomNumber}\", rng2) on nonNegativeInt.map(_.toString)" in {
    val s = RNG.map(RNG.nonNegativeInt)(_.toString)(rng)
    assert(s.isInstanceOf[(Int, RNG)]) // WRONG but PASS!!
    assert(s._2 !== rng)
}

现在,如果您发现错误的isInstanceOf[(Int, RNG)],您会认为这会导致失败,但是它会成功。

以下代码演示了只要元组具有正确的arity就会传递:

it should "not work" in {
    assert(("123", rng).isInstanceOf[(Int, RNG)]) // PASS
    assert(("123", rng).isInstanceOf[(String, Nothing)]) // PASS
    assert(("123", rng).isInstanceOf[(Exception, Array[_])]) // PASS
}

但是如果元组有一个类型参数:

it should "also not work" in {
    assert(("123").isInstanceOf[Int]) // FAIL
}

这里发生了什么?我该如何测试内部参数化类型?

1 个答案:

答案 0 :(得分:3)

不要忘记scala是由普通的旧java支持的,继承了它的所有细微差别。 Java对泛型类执行runtime type erasure。因此,运行时(Int, Rng)Tuple2(Object, Object)s也是如此。

您可以在scala here中找到有关如何解决该问题的一些有用信息。