【问题标题】:Why scala companion object's apply() returns Unit为什么 scala 伴随对象的 apply() 返回 Unit
【发布时间】:2017-05-15 02:08:20
【问题描述】:

我正在学习 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)
  }
}

main 中的Student("john", 29) 应该给出Student,但它返回Unit

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

【问题讨论】:

    标签: scala


    【解决方案1】:

    您已通过显式声明自己的 Student 伴随对象来覆盖编译器生成的默认 Student 伴随对象的行为

    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)
      }
    }
    

    把你的代码改成下面的代码 sn -p

    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)
      }
    }
    

    【讨论】:

    • scala 编译器可以通过使用正确的标志来检测这个错误:-Ywarn-value-discard。此处描述的其他有用标志:pedrorijo.com/blog/scala-compiler-review-code-warnings
    • 这个答案的第一句话令人困惑,因为Student是一个普通的类,而不是一个案例类。因此,没有像案例类那样的默认伴随对象。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-06
    • 2020-09-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多