Scala Newb
Scala Newb

Reputation: 281

Scala: The limits of _

Take:

var data = List[(DateTime, Double)]()
val pairs = io.Source.fromInputStream(getClass.getResourceAsStream("/data.csv")).getLines().map(_.split(","))
pairs.foreach(pair => data ::= (dateFormatter.parseDateTime(pair(0)), pair(1).toDouble))

No issues with that. If we decide to make use of the parameter placeholder instead of declaring pair, like so:

pairs.foreach(data ::= (dateFormatter.parseDateTime(_(0)), _(1).toDouble))

the compiler will not take it. Furthermore, the error:

too many arguments for method ::: (x: B)List[B]
pairs.foreach(data ::= (dateFormatter.parseDateTime(_(0)), _(1).toDouble))
                   ^

is not too helpful. What is going on here? I understand that the underscore cannot be used to represent more than one parameter, but it's only being used here as a stand-in for one parameter. I do not understand why the compiler will not take this, nor do I understand its reference to method :::, which is not being invoked.

Upvotes: 0

Views: 106

Answers (2)

thSoft
thSoft

Reputation: 22660

Underscores in a closure refer to the closure's parameters in declaration order, and cannot be used to refer to the same parameter.

Regarding the compiler error, it refers to the method ::, not ::: - the third colon is part of the error message, not of the method name! It is being invoked because of the assignment operator ::=.

Upvotes: 5

Richard Sitze
Richard Sitze

Reputation: 8463

The parameter placeholder _ can be used at most one time for each parameter.

So the first time it appears it maps to the first parameter, and the second time it appears it maps to the second parameter, and so forth. If there are more '_' than parameters, that's going to be a compilation problem.

Upvotes: 1

Related Questions