I saw that there are two methods to cast an object in Scala:
foo.asInstanceOf[Bar]
(foo: Bar)
When I tried, I found that asInstanceOf
Programming in Scala covers this in a bit of detail in Chapter 15 - Case Classes and Pattern Matching.
Basically the second form can be used as Typed Pattern in a pattern match, giving the isInstanceOf and asInstanceOf functionality. Compare
if (x.isInstanceOf[String]) {
val s = x.asInstanceOf[String]
s.length
} else ...
vs.
def checkFoo(x: Any) = x match {
case s: String => s.length
case m: Int => m
case _ => 0
}
The authors hint that the verbosity of the isInstance* way of doing things is intentional to nudge you into the pattern matching style.
I'm not sure which pattern is more effective for a simple type cast without a test though.