code

패키지 개체

codestyles 2020. 9. 7. 08:09
반응형

패키지 개체


개념이 아니라 사용법이 아닌 패키지 객체는 무엇입니까?

나는 작동하는 예제를 얻으려고 노력했고 내가 일해야 할 유일한 양식은 다음과 같습니다.

package object investigations {
    val PackageObjectVal = "A package object val"
}

package investigations {

    object PackageObjectTest {
        def main(args: Array[String]) {
            println("Referencing a package object val: " + PackageObjectVal)
        }
    }
}

지금까지 관찰 한 내용은 다음과 같습니다.

package object _root_ { ... }

허용되지 않음 (합리적 임)

package object x.y { ... }

또한 허용되지 않습니다.

패키지 객체는 직계 부모 패키지에 선언되어야하며, 위와 같이 작성하면 중괄호로 구분 된 패키지 선언 양식이 필요합니다.

그들은 일반적으로 사용됩니까? 그렇다면 어떻게?


일반적으로 패키지 객체를 package.scala해당하는 패키지에서 호출되는 별도의 파일에 넣습니다 . 중첩 된 패키지 구문을 사용할 수도 있지만 이는 매우 드문 경우입니다.

패키지 객체의 주요 사용 사례는 패키지에서 정의한 API를 사용할 때 패키지 내부 및 패키지 외부의 다양한 위치에서 정의가 필요한 경우입니다. 다음은 예입니다.

// file: foo/bar/package.scala

package foo

package object bar {

  // package wide constants:
  def BarVersionString = "1.0"

  // or type aliases
  type StringMap[+T] = Map[String,T]

  // can be used to emulate a package wide import
  // especially useful when wrapping a Java API
  type DateTime = org.joda.time.DateTime

  type JList[T] = java.util.List[T]

  // Define implicits needed to effectively use your API:
  implicit def a2b(a: A): B = // ...

}

Now the definitions inside that package object are available inside the whole package foo.bar. Furthermore the definitions get imported when someone outside of that package imports foo.bar._.

This way you can prevent to require the API client to issue additional imports to use your library effectively - e.g. in scala-swing you need to write

import swing._
import Swing._

to have all the goodness like onEDT and implicit conversions from Tuple2 to Dimension.


While Moritz's answer is spot on, one additional thing to note is that package objects are objects. Among other things, this means you can build them up from traits, using mix-in inheritance. Moritz's example could be written as

package object bar extends Versioning 
                          with JodaAliases 
                          with JavaAliases {

  // package wide constants:
  override val version = "1.0"

  // or type aliases
  type StringMap[+T] = Map[String,T]

  // Define implicits needed to effectively use your API:
  implicit def a2b(a: A): B = // ...

}

Here Versioning is an abstract trait, which says that the package object must have a "version" method, while JodaAliases and JavaAliases are concrete traits containing handy type aliases. All of these traits can be reused by many different package objects.


You could do worse than to go straight to the source. :)

https://lampsvn.epfl.ch/trac/scala/browser/scala/trunk/src/library/scala/package.scala

https://lampsvn.epfl.ch/trac/scala/browser/scala/trunk/src/library/scala/collection/immutable/package.scala


The main use case for package objects is when you need definitions in various places inside your package as well as outside the package when you use the API defined by the package.

Not so with Scala 3, scheduled to be released mid-2020, based on Dotty, as in here:

Toplevel Definitions

All kinds of definitions can be written on the toplevel.
Package objects are no longer needed, will be phased out.

package p 

type Labelled[T] = (String, T) 
val a: Labelled[Int] = ("count", 1) 
def b = a._2 
def hello(name: String) = println(i"hello, $name)

참고URL : https://stackoverflow.com/questions/3400734/package-objects

반응형