我正在学习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
。
任何解释都会有所帮助。谢谢!
答案 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)
}
}