Tuesday, June 21, 2016

Scala Beginners Issues


1. Compiling / Running  scala from command line just like javac /java

scalac com/PrintMesgObj.scala 
scala -classpath . com.PrintMesgObj

2. Common Errors:

package com

class PrintMsg {

  def main(args: Array[String]) = {
    println("Hello World !!")
  }
}

if you try to run the above code and expect Hello World to be printed, it won't. See the output
surjanrawat$ scalac com/PrintMsg.scala 
surjanrawat$ scala -classpath . com.PrintMsg
java.lang.NoSuchMethodException: com.PrintMsg.main is not static
at scala.reflect.internal.util.ScalaClassLoader$class.run(ScalaClassLoader.scala:68)

Reason: PrintMsg is class and to use this we need to define object of this class.

1.  Define object for PrintMsg
package com

object PrintMesgObj {
   val obj = new PrintMsg
   def main(args:Array[String])= {
     obj.main(args)
   }
}

surjanrawat$ scala -classpath . com.PrintMesgObj surjan
Hello World !!

Common Errors
1. java.lang.NoSuchMethodException: com.PrintMsg.main is not static
at scala.reflect.internal.util.ScalaClassLoader$class.run(ScalaClassLoader.scala:68)

2. scala -classpath . com.PrintMesgObj
java.lang.NoSuchMethodException: com.PrintMesgObj.main([Ljava.lang.String;)