Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
545 views
in Technique[技术] by (71.8m points)

casting - What are the differences between asInstanceOf[T] and (o: T) in Scala?

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 doesn't use implicit conversion whereas the other one does.

What are the differences of behavior between these two methods? And where is it recommended to use one over the other?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
  • 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

Ascribing type Int to a String 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...