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

后端 未结 4 1066
南笙
南笙 2020-11-30 00:40

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

4条回答
  •  一向
    一向 (楼主)
    2020-11-30 01:02

    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.

提交回复
热议问题