Monday, 10 November 2008

Scala: You cannot run a companion object as a stand-alone program

Update: In Scala 2.8, the below is no longer true. A companion object can now work as the entry point of an application.


In the Scala programming language, a companion object is an object with the same name as a class in the same source file. (Scala's companion objects can be used similar to Java's static methods.)

An object definition on its own can function as the entry point for running a Scala program. Compiling and running this object works fine:

object heyYouTheRocksteadyCrew{
def main(args :Array[String]) {
println("Make a break!")


However, if you try to run the same object when it is a companion object to a class with the same name, this will result in an exception:

class heyYouTheRocksteadyCrew{}

object heyYouTheRocksteadyCrew{
def main(args :Array[String]) {
println("Make a move!")


The above is true of the current release, (Until this is fixed, these guys will not be too happy about any stupid heyYouTheRocksteadyCrew-exception...!)

There is at least one thread about the above on the Scala mailing list.


Daniel said...

You _can_ run from the companion, of course. Only you need to use the fairly obscure Companion$.MODULE$ name.

Nikolaj Lindberg said...


thanks for pointing this out. The Companion$.MODULE$ thing was way too obscure for me :)