为什么scala伴侣对象的apply()返回Unit

时间:2017-05-14 18:05:46

标签: scala

我正在学习Scala。

class Student(var name:String, var age:Int) {
    private var sex:Int = 0
    println("class method")

    def apply() = {
       println("class apply method")
    }
}

object Student {
  def apply(name:String, age:Int): Unit = {
    println("object apply")
    new Student(name, age)
  }
  def main(args: Array[String]): Unit = {
    val student = Student("john", 29)
  }
}
Student("john", 29)中的

main假设提供Student,但会返回Unit

任何解释都会有所帮助。谢谢!

1 个答案:

答案 0 :(得分:3)

您已通过明确声明自己的学生伴侣对象来覆盖编译器生成的默认学生伴侣对象的行为

object Student {
  def apply(name:String, age:Int): Unit = { //Here is the problem. Return type is Unit instead of Student
    println("object apply")
    new Student(name, age)
  }
  def main(args: Array[String]): Unit = {
    val student = Student("john", 29)
  }
}

将您的代码更改为以下代码段

object Student {
  def apply(name:String, age:Int): Student = { //Changed the return type to Student
    println("object apply")
    new Student(name, age)
  }
  def main(args: Array[String]): Unit = {
    val student = Student("john", 29)
  }
}