Scala type judgment

Overview:

  • isInstanceOf: Determine whether the object is an object of the specified class
  • asInstanceOf: Convert the object to the specified type

format:

判断对象是否为指定类型:
var trueOrFalse: Boolean= 对象.isInstanceOf[类型]

将对象转换为指定类型:
val 变量 = 对象.asInstanceOf[类型]

Case study

demand:

  • Define a Person class
  • Define a Student class inherited from the Person class, which has a sayHello() method
  • Create a Student class object and specify its type as the Person type
  • Determine whether the object is of the Student type, if it is converted to the Student type, and call the sayHello() method

Reference Code:

object demo {
    
    
  class Person
  class Student extends Person {
    
    
    def sayHello(): Unit = println("Hello,Student")
  }

  def main(args: Array[String]): Unit = {
    
    
    var p:Person=new Student;
    //判断该对象是否为Student
    if (p.isInstanceOf[Student]){
    
    
      //是,转换为Student
      val s=p.asInstanceOf[Student];
      //调用sayHello()
      s.sayHello();
    }
  }
}

getClass和classOf

Overview: Because isInstanceOf can only determine whether an object is an object of a specified class and its subclasses, it cannot accurately determine that an object is an object of a specified class. If it is required to accurately determine that the type of the object is the specified data type, it can only be achieved by using getClass and classOf for a long time.

usage:

  • p.getClass can accurately obtain the type of object
  • classOf[class name] can accurately obtain the data type
  • Use == operator to directly compare types

Guess you like

Origin blog.csdn.net/zh2475855601/article/details/114679184