2

using the ScalaTest/FlatSpec library I am testing the types of returned values from a random number generator using functional state:

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)
}

now if you notice the incorrect isInstanceOf[(Int, RNG)] you would think that this would produce a fail, however it succeeds.

the following code demonstrates that this passes as long as the tuple has the correct 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
}

but if the tuple has one type parameter:

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

What is going on here? how should I test the inner parameterized types?

coderatchet
  • 7,214
  • 15
  • 60
  • 109

1 Answers1

3

Don't ever forget that scala is backed by plain old java, inheriting all its nuances. Java performs runtime type erasure for generic classes. So your (Int, Rng) in runtime is Tuple2(Object, Object), so is your s.

You can find some useful information how to work around that issue in scala here.

Community
  • 1
  • 1
Aivean
  • 8,465
  • 20
  • 26