Type与Class

class Spark
trait Hadoop
object Flink //单例
class Java{
  class Scala
}
object Type_Advanced {

  def main(args: Array[String]) {
    println(typeOf[Spark]) //结果:com.dt.scala.bestpractice.Spark
    println(classOf[Spark]) //Class[_ <: Spark],结果:class com.dt.scala.bestpractice.Spark
    
    val spark = new Spark
    println(spark.getClass); //结果:class com.dt.scala.bestpractice.Spark
    
    println(classOf[Hadoop]) //结果:interface com.dt.scala.bestpractice.Hadoop
    println(typeOf[Hadoop]) //结果:com.dt.scala.bestpractice.Hadoop
    
    println(Flink.getClass) //结果:class com.dt.scala.bestpractice.Flink$,这个$说明,在Scala中,object背后也是有类的
// println(classOf[Flink])
    
    val java1 = new Java
    val java2 = new Java
    val scala1 = new java1.Scala
    val scala2 = new java2.Scala
    println(scala1.getClass) //结果:class com.dt.scala.bestpractice.Java$Scala
    println(scala2.getClass) //结果:class com.dt.scala.bestpractice.Java$Scala
    println(typeOf[java1.Scala] == typeOf[java2.Scala]) //false
    println(typeOf[java1.Scala]) //结果:java1.Scala
    println(typeOf[java2.Scala]) //结果:java2.Scala
    
    //type是更详细的信息,而class是更抽象的信息

    println(classOf[List[Int]] == classOf[List[String]]) //true
    println(typeOf[List[Int]] == typeOf[List[String]]) //false
    println(classOf[List[Int]]) //class scala.collection.immutable.List
    println(classOf[List[String]]) //class scala.collection.immutable.List
    println(typeOf[List[Int]]) //scala.List[Int]
    println(typeOf[List[String]]) //scala.List[String]
  }
}

你可能感兴趣的:(Type与Class)