0

I am very new to Scala, I try some tutorials but I didn't get the point in this problem here:

val reverse = new mutable.HashMap[String, String]() with mutable.SynchronizedMap[String, String]  

def search(query: String) = Future.value {
  val tokens = query.split(" ")
  val hits = tokens map { token => reverse.getOrElse(token, Set()) }
  if (hits.isEmpty)
    Nil
  else
    hits reduceLeft {_ & _} toList // value & is not a member of java.lang.Object
}

The compiler says value & is not a member of java.lang.Object. Can somebody explain me why I am getting a compiler error ? I have this from this tutorial here: https://twitter.github.io/scala_school/searchbird.html

2
  • The future object has no method value, you have to move it after the curly bracket. Commented Oct 15, 2014 at 15:59
  • I edited the source, I forgot the "reverse" and the "toList". The problem is at the last line with the binary operation "&" Commented Oct 15, 2014 at 16:07

2 Answers 2

4

"tokens" is of type Array[String]. Now, when you iterate over the array, there are two possibilities. Either reverse will have a value for the token or not. If it has, then the Array element get a string value otherwise an empty set.

For example: Lets say reverse has two values - ("a" -> "a1", "b" ->"b1") a maps to a1 and b maps to b1.

Suppose, The query string is "a c". tokens will be ["a","c"] after splitting. After mapping you will get in array ["a1", Set()] (a got mapped to a1 and there is no value for "c" in the map hence, you got an empty Set())

Now, the overall type of the hits array is Array[Object]. So, now you are getting an error as the last line will be "&" operator on 2 Objects according to the compiler.

Sign up to request clarification or add additional context in comments.

Comments

2

Mohit Has The right answer, you end up with an Array of objects. This is because your HashMap for reverse has a value type of String, so it'll return a String for a given key. Your getOrElse however, will return a Set type if the key is not found in your HashMap reverse. These need to return the same type so you don't end up with an Array[Objects]

If you notice a few lines above in the tutorial you linked, reverse is defined as follows:

val reverse = new mutable.HashMap[String, Set[String]] with mutable.SynchronizedMap[String, Set[String]]

1 Comment

Thank you. Maybe I overlooked this detail.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.