small medium large xlarge

22 Dec 2009, 13:02
Shih-gian Lee (5 posts)

Hi Venkat,

I read your Programming in Groovy and now your Programming in Scala. Programming in Scala is just as good as Programming in Groovy. Thank you for the great book!

I tried to compile the Static.scala from command line using scalac:

class Marker private (val color: String) {
  override def toString() : String = "marker color " + color

object Marker {
  private val markers = Map( 
    "red" -> new Marker("red"), 
    "blue" -> new Marker("blue"), 
    "green" -> new Marker("green")

  def primaryColors = "red, green, blue"

  def apply(color: String) = if (markers.contains(color)) markers(color) else null

println("Primary colors are : " + Marker.primaryColors)

But, I am getting the following error:

Static.scala:20: error: expected class or object definition
println("Primary colors are : " + Marker.primaryColors)
Static.scala:21: error: expected class or object definition
Static.scala:22: error: expected class or object definition
three errors found

I am using Scala 2.7.7. Did I do something wrong?

Thank you in advance for your help!

Thanks, Lee

23 Dec 2009, 01:34
Venkat Subramaniam (86 posts)

Hi Lee,

You would have noticed the code works fine when you run using scala, but as you pointed out, it fails when you compile using scalac. That’s because the scala compiler expects you to provide a full class to compile instead of script. If you want to compile it using scalac, you could wrap the last three executable statements into a singleton like

//…code ending with END:DEF goes here… object Static { def main(args: Array[String]) { //START:USE println(“Primary colors are : “ + Marker.primaryColors) println(Marker(“blue”)) println(Marker(“red”)) //END:USE } }

and then compile the entire code using scalac. You can then run using the java command (make sure you provide the path to scala library).

Hope this helps. Thanks for your comments.



23 Dec 2009, 03:13
Shih-gian Lee (5 posts)

Hi Venkat,

That makes sense now. I confused scalac with scala. I thought scalac would roll the code into the traditional main( ) method of a Main class just like scala.

Thanks for pointing out!

Regards, Lee

You must be logged in to comment