In Scala, how do you define a local parameter in the primary constructor of a class?

后端 未结 4 2051
走了就别回头了
走了就别回头了 2020-12-16 22:32

In Scala, how does one define a local parameter in the primary constructor of a class that is not a data member and that, for example, serves only to initialize a data membe

4条回答
  •  一向
    一向 (楼主)
    2020-12-16 22:46

    Derek,

    If you have this:

    class A(a: Int) {
      val aa = a // reference to constructor argument in constructor code (no problem)
      def m: Float = a.toFloat // reference to constructor argument in method body (causes a to be held in a field)
    }
    

    you'll find (using javap, e.g.) that a field named "a" is present in the class. If you comment out the "def m" you'll then see that the field is not created.

提交回复
热议问题