no static forwarder in companion trait

scala

If you ever write main method in the trait companion object and try to run the main function, you will get error “no static forwarder methods in companion trait”. Or you compile the code only, you get warning “no static forwarder can be generated”. That’s weird, right?  How come?

trait Test {
	def hi(): Unit
}

object Test {
 def main(args: Array[String]): Unit = {
   System.out.println("hello world");
 }
}

Scala will compile to java bytecode for interoperability with java. And for trait, it will compile to java interface. As we talked in the post https://leecy.me/scala-object-and-static-forwarder/, when you call the method in object, you are actually forwarding to the singleton instance’s method calling.

Before jdk8, there’s no static method can be added to interface. So it’s not possible to generate a static main function in the trait as an execution entry. See below class file. main is an instance method in Test$ class but not static method.

What about test is a class?

class Test2 {
 def hi(): Unit = {}
}
object Test2 {
 def main(args: Array[String]): Unit = {

 }
}

Let’s compiled and inspect the class file again. We can see static main method is generated.

That solves the puzzle. All lies on the generated main method.