0
object myClass is not a member of package <root>
import _root_.myClass
//test1.scala 
import _root_.myClass

object test1 {
  def main(args:Array[String]): Unit = {
    println(this.getClass.getName)
  }
}
//myClass.scala 
case class myClass(){
}

Everthing... renaming the class to include the root ... Note that they are not in the same file

Th333w1
  • 19
  • 1
  • 4

1 Answers1

2

Indeed, myClass is not a member of package _root_. It's in the package _empty_.

If you put everything in the package mypackage then you'll be able to import with _root_

src/main/scala/mypackage/test1.scala

package mypackage

import _root_.mypackage.myClass

object test1 {
  def main(args:Array[String]): Unit = {
    println(this.getClass.getName)
  }
}

src/main/scala/mypackage/myClass.scala

case class myClass()

For myClass from my code, scala.reflect.runtime.universe.symbolOf[myClass].owner returns package mypackage. For myClass from your code, it returns package <empty>.

A couple of quotes from the spec:

https://scala-lang.org/files/archive/spec/2.13/09-top-level-definitions.html

Top-level definitions outside a packaging are assumed to be injected into a special empty package. That package cannot be named and therefore cannot be imported. However, members of the empty package are visible to each other without qualification.

If a package name is shadowed, it's possible to refer to its fully-qualified name by prefixing it with the special predefined name _root_, which refers to the outermost root package that contains all top-level packages.

The name _root_ has this special denotation only when used as the first element of a qualifier; it is an ordinary identifier otherwise.

What is the _root_ package in Scala?

scala: can't import object from root scope

Why is my object not a member of package <root> if it's in a separate source file?

Dmytro Mitin
  • 48,194
  • 3
  • 28
  • 66
  • Please note that the code isn't in the same file. – Th333w1 Apr 28 '23 at 15:42
  • @Th333w1 Ok, I modified my answer. This doesn't change much. Important is that `myClass` and `test1` are in the same package, not that they are in the same file. Anyway you don't have to import a class from the same package. – Dmytro Mitin Apr 28 '23 at 15:47