Question

I am new to Scala and I am having trouble with an example from the book Scala in Action.

I am using IntelliJ, but I've also tried it as script (REPL). The scala compiler gives me the same error as IntelliJ. (I am using Scala 2.10, as the book suggest).

Here is my code:

def parseArgs(args: Array[String]): Map[String, List[String]] = {
val command = args.head
val params  = parseArgs(args)
val url = args.last

def nameValuePair(paramName: String) = {
  def values(commaSeparatedValues: String) = commaSeparatedValues.split(",").toList
  // x => x + 2
  val index = args.indexOf(_ == paramName)
  (paramName, if(index == -1) Nil else values(args(index + 1)))
}

  Map(nameValuePair("-d"), nameValuePair("-h"))
}

The message I get is:

C:\scala\projects\scripts\restclientscript.scala:12: error: missing parameter type for expanded function ((x$1) => x$1.$eq$eq(paramName))
val index = args.indexOf(_ == paramName)
                         ^
one error found

This is exactly as it is shown in the book but I can't figure out how to make it work.

Also the method indexOf is actually findIndexOf in the book. But that method does not exist the compiler tells me (and the doc: http://www.scala-lang.org/api/2.10.3/index.html#scala.Array).

Lastly, IntelliJ will not accept the == inside the indexOf() method (highlighted red, but compiles).

Any help would be appreciated! :)

Was it helpful?

Solution

The book may be referring to an older version of Scala. Looking at the doc page you linked it is clear that the method indexOf has the following signature:

indexOf(elem: T): Int

That means that the method doesn't expect a closure but instead a value. You probably want to use indexWhere:

indexWhere(p: (T) ⇒ Boolean): Int

That should work!

One more advice is: never trust IntelliJ Idea errors, always double check them with sbt as Idea uses a different algorithm for checking errors and doesn't rely on the actual compiler.

OTHER TIPS

Array.indexOf takes an instance for which the index should be found in the array.

If you want a version with predicate, there's Array.indexWhere (at least according to Scala 2.11 docs) which takes a predicate function p : (T) => Boolean.

So, you can either do:

args.indexOf(paramName)

or

args.indexWhere(_ == paramName)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top