tags:

views:

323

answers:

3

I saw that there is 2 methods to cast an object :

foo.asInstanceOf[Bar]
(foo: Bar)

When I tried I found that as asInstanceOf don't use the implicit conversions whereas the other one do.

So what are the differences of behavior between this 2 methods ? And where it's recommended to use one over the other ?

Thank you.

+3  A: 

"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 typecast without a test though.

Jon McAuliffe
+24  A: 
  • foo.asInstanceOf[Bar] is a type cast, which is primarily a runtime operation. It says that the compiler should be coerced into believing that foo is a Bar. This may result in an error (a ClassCastException) if and when foo is evaluated to be something other than a Bar at runtime.

  • foo:Bar is a type ascription, which is entirely a compile-time operation. This is giving the compiler assistance in understanding the meaning of your code, without forcing it to believe anything that could possibly be untrue; no runtime failures can result from the use of type ascriptions.

Type ascriptions can also be used to trigger implicit conversions. For instance, you could define the following implicit conversion:

implicit def foo(s:String):Int = s.length

and then ensure its use like so:

scala> "hi":Int                                 
res29: Int = 2

Ascripting a String as an Int would normally be a compile-time type error, but before giving up the compiler will search for available implicit conversions to make the problem go away. The particular implicit conversion that will be used in a given context is known at compile time.

Needless to say, runtime errors are undesirable, so the extent to which you can specify things in a type-safe manner (without using asInstanceof), the better! If you find yourself using asInstanceOf, you should probably be using match instead.

pelotom
One case where type annotation is needed is when you want to specify the type for null, e.g. when using Java APIs.
Landei
Thanks for this great explanation !
Mr_Qqn
@pelotom: Hey your example is great! "hi":Int ... I have never seen or used implicits that way but truly an interesting thing.
soc
`foo: Bar` is known as _type ascription_. It would be good to use this terminology, as it makes it easier to find more information about it. Or to locate this answer when searching for it. :-)
Daniel
@Daniel thanks, fixed.
pelotom
+1 to Daniel for the term type ascription. Wouldn't have know that otherwise
I82Much
+9  A: 

Pelotom's answer covers the theory pretty nice, here are some examples to make it clearer:

def foo(x: Any) {
  println("any")
}

def foo(x: String) {
  println("string")
}


def main(args: Array[String]) {
  val a: Any = new Object
  val s = "string"

  foo(a)                       // any
  foo(s)                       // string
  foo(s: Any)                  // any
  foo(a.asInstanceOf[String])  // compiles, but ClassCastException during runtime
  foo(a: String)               // does not compile, type mismatch
}

As you can see the type ascription can be used to resolve disambiguations. Sometimes they can be unresolvable by the compiler (see later), which will report an error and you must resolve it. In other cases (like in the example) it just uses the "wrong" method, not that you want. foo(a: String) does not compile, showing that the type ascription is not a cast. Compare it with the previous line, where the compiler is happy, but you get an exception, so the error is detected then with the type ascription.

You will get an unresolvable ambiguity if you also add a method

def foo(xs: Any*) {
  println("vararg")
}

In this case the first and third invocation of foo will not compile, as the compiler can not decide if you want to call the foo with a single Any param, or with the varargs, as both of them seems to be equally good => you must use a type ascription to help the compiler.

Edit see also What is the purpose of type ascription in Scala?

Sandor Murakozi
+1 nice concrete examples
pelotom