ilango
ilango

Reputation: 1287

How to use the Scala import clause to import from a method parameter

I wrote a Scala source file called Vegetables.scala. What I am trying to accomplish from this code below is to understand how import clauses work. I typed in this program in Eclipse and started the Eclipse-based REPL. What I would like to do is create a new object called Spinach that extends Vegetable, assign it to a val and eventually invoke the showColor method of object Vegetable, passing the Spinach object into it. I know the examples sounds absurd, but I simply trying to understand the concepts/mechanics of Scala right now. To this end I did the following in the REPL:

So this is what I did on the REPL and get an error.

import com.att.scala.Vegetables._
import java.awt.Color
val obj = object Spinach extends Vegetable { val name = "Spinach" val color = Color.GREEN }

<console>:1: error: illegal start of simple expression
       val obj = object Spinach extends Vegetable { val name = "Spinach" val color = Color.GREEN }
                 ^

The code for Vegetable.scala is below:

 package com.att.scala
 import java.awt.Color

 trait Vegetable {
  val name: String
  val color: Color
}

  object Vegetables {
    object Asparagus extends Vegetable { 
      val name = "Asparagus"
      val color = Color.GREEN  
  } 

object Carrot extends Vegetable { 
  val name = "Carrot"
  val color = Color.ORANGE 
 }
val veggiePlatter = List(Asparagus, Carrot)

 def showColor(veggie: Vegetable) {
   import veggie._
   println("Entered showColor")
   import veggie._
   println("veggie color is " + color)
  }
}

What might explain this error? Firstly, I am trying to understand what is the right way to make an object on the REPL and then assign it to a val. Once that is out of the way, I hope to pass that val in a parameter. Then, I would like to test the import clause inside the showColor to see if it indeed imports the members of the veggie parameter.

Upvotes: 0

Views: 6538

Answers (1)

Andrzej Doyle
Andrzej Doyle

Reputation: 103787

Defining an object is like defining a static member, or a class. You can't declare it and assign it to a variable at the same time. (And in fact you don't really need to, as the object can already be accessed via its name after it's defined.)

So your example would work in the REPL as:

import com.att.scala.Vegetables._
import java.awt.Color
object Spinach extends Vegetable { val name = "Spinach" val color = Color.GREEN }

which would define an object called Spinach. After that, you could call Vegetables.showColor(Spinach) to achieve your initial goal.

If you really wanted to assign it to a variable, you could call val obj = Spinach after you've declared the object, which would be valid (albeit not particularly useful - Spinach is already an unambiguous name for that thing, obj would effectively just be an alias.). Doing it on the same line that you declare the object though is illegal syntax.

Upvotes: 3

Related Questions