Stephen Carman
Stephen Carman

Reputation: 997

Scala top level package object

Edited this question to be more clear, see comments below for explanation.

So this seems kinda obvious to me, but it doesn't seem like it works that way, but if I have a scala package object and it's in the top level of my packages. Say like com.company and it's something simple like below

package com

package object company{
  val something = "Hello world."
}

Now it would seem to me that this variable would trickle down and be accessible from it's child packages, but they aren't.

// 2 Layers down instead of the direct child
package com.company.app

import com.company._

object Model extends App {
  println(something)
}

This seems to only work with the import, which is fine, but I was hoping with the package object I could define top level things for the entire package and have it trickle down, but is that not the case? Is there a way for this to work? I appreciate any insight into this.

Upvotes: 8

Views: 1670

Answers (1)

Rüdiger Klaehn
Rüdiger Klaehn

Reputation: 12565

The code posted in your question works as it is without an import. If you want the definitions of all packet objects above your current package to trickle down, you will have to modify the package statement of the classes in subpackages

Package object

package com

package object company {
  val something = "Hello world."
}

Class in a subpackage com.company.model

package com
package company
package model
// package com.company.model would not work here!

object Model extends App {
  println(something)
}

This technique is used frequently in the scala library itself. See for example the package statement in s.c.i.HashSet:

package scala
package collection
package immutable

Upvotes: 4

Related Questions