Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala top level package object

Tags:

scala

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.

like image 757
Stephen Carman Avatar asked Nov 19 '15 14:11

Stephen Carman


1 Answers

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
like image 188
Rüdiger Klaehn Avatar answered Oct 23 '22 19:10

Rüdiger Klaehn