scala notes - implicit conversions

Knowledge point: Implicit conversion (Purpose: Implicit enhancement of class methods)

 

Test code:

package demo.scala

/**
  * Implicit conversion
  * Purpose: Implicitly extend the method of the class
  */
object TestImplicit {

  def main(args: Array[String]): Unit = {
    var student = new Student

    //Implicit conversion function, convert Student to Teacher
    implicit def student2Teacher(student: Student) = new Teacher
    //student has the teach function of teacher
    student.teach()
    //student's own study method
    student.study()
  }

  class Teacher {

    def teach(): Unit = {
      println("teach")
    }
  }

  case class Student() {

    def study(): Unit = {
      println("study")
    }
  }

}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326175668&siteId=291194637