在 Scala 中创建非法循环引用错误的错误是什么以及为什么是错误的?

问题描述

我试图从基本面的角度来理解它。这个问题很幼稚,但答案会让进入 OOP 或刚接触编程范式的人更加清晰。

它从 python 开始,当我尝试使用一些 OOP 示例代码时,如下所示:

class Student(ScienceStudent):

    def __init__(self): 
        self.name = input("Enter name")
        self.age = input("Enter age")

    def put_data(self):
        print(self.name)
        print(self.age)

class ScienceStudent(Student):

    def science(self):
        print("This person kNows science")

student1 = Student()
student2 = ScienceStudent()

student1.put_data()
student2.put_data()
student2.science()
student1.science()

导致错误

Traceback (most recent call last):
File "xyz.py",line 1,in <module>
class Student(ScienceStudent):
NameError: name 'ScienceStudent' is not defined

现在我在 Scala 中做了类似的事情:

object HelloWorld extends App { 
    println("Hello,World!")    
}

class Student extends ScienceStudent {  
  def study(in: String): Boolean = {
    if (in == "y") {
      return true
    }
    else {
      return false
    }
  }  
}

class ScienceStudent extends Student {  
  def scifi(): Unit = {
    println("I kNow science")
  }
}

我得到了错误

HelloWorld.scala:20: error: illegal cyclic reference involving class Student

现在,我想听。

解决方法

Scala 中的一个具体原因(忽略在继承图中具有循环的本体含义)是扩展类 A 的类 B 的构造函数必须始终调用类 { 的构造函数{1}} 以初始化从 B 继承的 A 的任何状态。