Question about methods in package directly

sorry I am just newbie.

i know methods/variables can’t be put in a package directly.

package A

def mytest = { }

doesn’t work.

but if I do want to access a method from a package name, such as:

A.mytest()

do you think if it’s possible?

thanks

Welcome to Scala, @frakass

Instead of trying to guess the syntax/semantics (like how so many newbies keep wasting their time), take a look at Chapter 12: “Packages, Imports and Exports” from “Programming in Scala, 5th Edition” co-authored by the language creator.

In Scala 3, you can actually define top-level vals and defs.

In Scala 2, you can use package objects to achieve something similar:

package object foo {
  def mytest(): Int = 5
}

By convention, this is put in a file named <sources>/foo/package.scala. Note that there is no package foo above that definition.

For a subpackage foo.bar it looks like:

package foo // the "parent" package

package object bar {
  def mytest(): Int = 5
}

in the file <sources>/foo/bar/package.scala.

2 Likes