【Scala五】分析Spark源代码总结的Scala语法三

1. If语句作为表达式

    val properties = if (jobIdToActiveJob.contains(jobId)) {
      jobIdToActiveJob(stage.jobId).properties
    } else {
      // this stage will be assigned to "default" pool
      null
    }

 

2.asInstanceOf方法

像是协变,

scala> val a = List(1,2,3);
a: List[Int] = List(1, 2, 3)

scala> val b = a.asInstanceOf[List[Number]]
b: List[Number] = List(1, 2, 3)

scala> b(1)
res0: Number = 2

 

 

///向上转型
scala> val b = a.asInstanceOf[Int]
b: Int = 10

scala> val b = a.asInstanceOf[Any]
b: Any = 10

 

只能做协变和向上转型,如下操作是不行的,

 

如下是不可以的

scala> val a=10
a: Int = 10

scala> val b = a.asInstanceOf(String)

scala> val b = a.asInstanceOf[String]
java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
        at .<init>(<console>:8)
        at .<clinit>(<console>)
        at .<init>(<console>:7)
        at .<clinit>(<console>)
        at $print(<console>)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.ja
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccesso
        at java.lang.reflect.Method.invoke(Method.java:606)
        at scala.tools.nsc.interpreter.IMain$ReadEvalPrint.call(IMain.scala:734)

 

你可能感兴趣的:(scala)