Scala underscore - ERROR: missing parameter type for expanded function

ScalaScala Placeholder-Syntax

Scala Problem Overview


I know there have been quite a few questions on this, but I've created a simple example that I thought should work,but still does not and I'm not sure I understand why

val myStrings = new Array[String](3)
// do some string initialization

// this works
myStrings.foreach(println(_))


// ERROR: missing parameter type for expanded function
myStrings.foreach(println(_.toString))

Can someone explain why the second statement does not compile?

Scala Solutions


Solution 1 - Scala

It expands to:

myStrings.foreach(println(x => x.toString))

You want:

myStrings.foreach(x => println(x.toString))

The placeholder syntax for anonymous functions replaces the smallest possible containing expression with a function.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJeff StoreyView Question on Stackoverflow
Solution 1 - ScalaretronymView Answer on Stackoverflow