Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Missing Parameter Type For Expanded Function

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! :)

like image 910
thomas77 Avatar asked Feb 12 '23 23:02

thomas77


2 Answers

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.

like image 57
Aldo Stracquadanio Avatar answered Feb 16 '23 03:02

Aldo Stracquadanio


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)
like image 24
Patryk Ćwiek Avatar answered Feb 16 '23 04:02

Patryk Ćwiek