Schroedinger
Schroedinger

Reputation: 1283

Accessing a set on an object in scala

I've currently put together the following code that does recognise elements and allegedly add them to the set but when I print out the set the set is filled with functions

class PropositionOrderer extends Identity{
    var Names = SortedSet[Name] _
    override def variable = {
      _ match {
        case name => 
          Names+(name)
          Variable(name)
      }
    }
}

I want to then call it on a proposition and get the sorted list of names in the proposition

type Names = SortedSet[Name]
  val Names = SortedSet[Name] _
  def vars: Proposition => Names =
  {
    case p => 
      val prop = new PropositionOrderer
      prop.visit(p)
      println(prop.Names)
      //this just to fit the return definition
      Names("Dan","Web")
  }

If I return prop.Names it says that I'm returning an object of the wrong type. Any ideas?

Upvotes: 0

Views: 82

Answers (1)

dhg
dhg

Reputation: 52681

There are several problems here. I will list a few. Correcting these should get you on track.

First, you defining Names in two different ways, which is no good. It looks like you meant for it to be a type, so stick with that.

type Names = SortedSet[Name]   // this defines a new type called `Names`
val Names = ...                // this defines a variable called `Names`

Next, if you want to define a new, empty SortedSet, the syntax is as below. (Note that variable names should always be lowercase. Uppercase is reserved for type names.)

val names = SortedSet[Name]()   // `names` is a new `SortedSet`
val Names = SortedSet[Name] _   // `Names` is a function that takes multiple `Name` arguments and constructs a `SortedSet`

Third, if you want to add something to the Set, you have to use +=, otherwise the existing set doesn't change.

var names = SortedSet[String]()
names + "test"   // `names` is unchanged
names += "test"  // `names` is updated

Upvotes: 3

Related Questions