Black monkey house: Scala package object

Package can contain classes, objects and character trait, but can not contain the definition of the function or variable. Unfortunately, this is a limitation of the Java virtual machine.

Add the tool to function or package instead of a constant Utils object, which is a more reasonable approach.

Appearance package object is to solve this limitation. Each package can have a package object. You need to define it in the parent package and the child package with the same name. After the Java virtual machine at compile time, Java is not supported, Scala is always good at breaking this limitation, Scala break out, and then obediently go back, just to facilitate the development, the scala compiler, or .Class file, put it inside jvm run

package com.nick.impatient

package object people {
  val defaultName = "Nick"
}
package people {
  class Person {
    var name = defaultName // 从包对象拿到的常值
  }
}

Reproduced in: https: //www.jianshu.com/p/a6fa8a041599

Guess you like

Origin blog.csdn.net/weixin_33690367/article/details/91182484