Scala: Importing packages into package objects

你说的曾经没有我的故事 提交于 2021-01-28 08:08:47

问题


I'm having trouble importing packages into package objects. It didn't seem to work in Eclipse and so I switched to intellij. At one point the feature seemed to be working and so I created package objects for most packages. Now it doesn't seem to be working at all. Here's a package object in file package.scala, the package file itself compiles fine:

package rStrat.rSwing
package testSw //Edited for clarity

object testSw
{
  import rStrat._
  import rSwing.topUI._
}

and here's a class file from the same module and package.

package rStrat.rSwing.testSw

object MainTest {
  def main(args: Array[String])
  {
    val testApp = new AppWindow //Appwindow is a member of topUI
    testApp.open
  }
}

It works fine if I import the topUI package straight into the MainTest file. it makes no difference whether I try and import the whole package or a particular class. is this legal scala? Is the problem with the IDEs?

I'm using Scala 2.92 Final, Intellij 11.1.1, JDK 1.6.0_31, Eclipse 3.7.2


回答1:


Scala does not have first class imports. Where a package can only contain declarations of classes and traits, a package object can contain any other valid Scala declaration like var, val, def, type (type alias), implicit stuff. And although as in any object you can import things, they don't transitively propagate to the rest of the package and are thus not visible to the rest of the world.




回答2:


This creates the object rStrat.rSwing.testSw.testSw:

package rStrat.rSwing
package testSw //Edited for clarity

object testSw

This creates the package object rStrat.rSwing.testSw.testSw:

package rStrat.rSwing
package testSw //Edited for clarity

package object testSw

This creates the package object rStrat.rSwing.testSw:

package rStrat.rSwing

package object testSw

It's the last one you want.



来源:https://stackoverflow.com/questions/10521706/scala-importing-packages-into-package-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!