Type與Class

541732025發表於2016-03-17

點選(此處)摺疊或開啟

  1. class Spark
  2. trait Hadoop
  3. object Flink //單例
  4. class Java{
  5.   class Scala
  6. }
  7. object Type_Advanced {

  8.   def main(args: Array[String]) {
  9.     println(typeOf[Spark]) //結果:com.dt.scala.bestpractice.Spark
  10.     println(classOf[Spark]) //Class[_ <: Spark],結果:class com.dt.scala.bestpractice.Spark
  11.     
  12.     val spark = new Spark
  13.     println(spark.getClass); //結果:class com.dt.scala.bestpractice.Spark
  14.     
  15.     println(classOf[Hadoop]) //結果:interface com.dt.scala.bestpractice.Hadoop
  16.     println(typeOf[Hadoop]) //結果:com.dt.scala.bestpractice.Hadoop
  17.     
  18.     println(Flink.getClass) //結果:class com.dt.scala.bestpractice.Flink$,這個$說明,在Scala中,object背後也是有類的
  19. // println(classOf[Flink])
  20.     
  21.     val java1 = new Java
  22.     val java2 = new Java
  23.     val scala1 = new java1.Scala
  24.     val scala2 = new java2.Scala
  25.     println(scala1.getClass) //結果:class com.dt.scala.bestpractice.Java$Scala
  26.     println(scala2.getClass) //結果:class com.dt.scala.bestpractice.Java$Scala
  27.     println(typeOf[java1.Scala] == typeOf[java2.Scala]) //false
  28.     println(typeOf[java1.Scala]) //結果:java1.Scala
  29.     println(typeOf[java2.Scala]) //結果:java2.Scala
  30.    
  31.     //type是更詳細的資訊,而class是更抽象的資訊

  32.     println(classOf[List[Int]] == classOf[List[String]]) //true
  33.     println(typeOf[List[Int]] == typeOf[List[String]]) //false
  34.     println(classOf[List[Int]]) //class scala.collection.immutable.List
  35.     println(classOf[List[String]]) //class scala.collection.immutable.List
  36.     println(typeOf[List[Int]]) //scala.List[Int]
  37.     println(typeOf[List[String]]) //scala.List[String]
  38.   }

  39. }

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/28912557/viewspace-2058807/,如需轉載,請註明出處,否則將追究法律責任。

相關文章