本文介绍了在Scala中asInstanceOf [T]和(o:T)之间有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到在Scala中有两种方法来转换对象:

I saw that there are two methods to cast an object in Scala:

foo.asInstanceOf[Bar]
(foo: Bar)



当我尝试时,我发现 asInstanceOf 不使用隐式转换,而另一个。

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?

推荐答案


  • foo.asInstanceOf [Bar] 是一种类型强制转换,主要是运行时操作。它说,编译器应该被强制认为 foo Bar 。这可能会导致错误( ClassCastException )if和 foo 被评估为<$

    • 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 类型归属,这完全是编译时操作。这是给编译器帮助理解你的代码的意义,而不强迫它相信任何可能是不真实的;

      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
      

      订阅类型 Int String 通常是编译时类型错误,但在放弃之前,编译器将搜索可用的隐式转换,问题消失。在给定上下文中使用的特定隐式转换在编译时是已知的。

      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.

      不用说,运行时错误是不希望的,因此,以类型安全方式(不使用 asInstanceof ),更好!如果你发现自己使用 asInstanceOf ,你可能应该使用 match

      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.

      这篇关于在Scala中asInstanceOf [T]和(o:T)之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-19 01:16