1

I have written the following scala script in ammonite shell

#!/usr/bin/env amm
@main
def main() = {
    val p = Person("foo")
}

case class Person(name: String)

This compiles and works fine. But I need the class Person to be in a package called com.foo

If I try

#!/usr/bin/env amm
@main
def main() = {
    val p = Person("foo")
}

package com.foo {
  case class Person(name: String)
}

Now I get a syntax error which is like

Syntax Error: End:7:1 ..."package co"
package com.foo {

I wonder how can I specify the namespace for my case class. Since its a script, I would like to keep everything in the same file.

Knows Not Much
  • 30,395
  • 60
  • 197
  • 373

1 Answers1

2

Since the script content is wrapped by Ammonite in an object (to have top-level statements and definitions), you cannot use package. But you can namespace your class by defining it in a nested object:

object com {
  object foo {
    case class Person(name: String)
  }
}

@main
def main() = {
  val p = com.foo.Person("foo")
}

If you will later import this script in another one, you will also use this namespace (without the wrapping):

import $file.firstScript, firstScript._

println(com.foo.Person("Bob"))
laughedelic
  • 6,230
  • 1
  • 32
  • 41
  • This technique is ok, but what about is I have to pass a full class name to Jython, or to dynamically create an object given its full class name? – david.perez Aug 26 '21 at 10:54