scalaammonite

Create a class with a package in a Scala Ammonite Script


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.


Solution

  • 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"))