This page is no longer maintained — Please continue to the home page at www.scala-lang.org

wildcard formal parameters

3 replies
Andy 2
Joined: 2010-11-07,
User offline. Last seen 42 years 45 weeks ago.

This may be a very stupid question, but I'll try it anyway

Alexey Romanov
Joined: 2010-06-04,
User offline. Last seen 42 years 45 weeks ago.
Re: wildcard formal parameters

On Sun, Nov 7, 2010 at 8:22 AM, Andy wrote:
> This may be a very stupid question, but I'll try it anyway

extempore
Joined: 2008-12-17,
User offline. Last seen 35 weeks 3 days ago.
Re: wildcard formal parameters

On Sun, Nov 07, 2010 at 05:22:45AM +0000, Andy wrote:
> Section 6.23 in "The Scala Language Specification, version
> 2.8" says, regarding anonymous functions, that:
>
> "A formal parameter may also be a wildcard represented by
> an underscore _. In that case, a fresh name for the
> parameter is chosen arbitrarily."

That means this:

val f: Int => Int = _ => 5

> I've interpreted that as ...

something other than what it is trying to communicate.

The relevant portion of the spec is "Placeholder Syntax for Anonymous
Functions" which directly follows that.

The rest of your email seems to be everyone's initial difficulty with
how underscores expand. You are rather ambitiously not only trying for
the usual "hop the parentheses" but pushing into the unknown territory
of "start a block and drop into some later statement." My magic 8-ball
says "outlook not good."

> This may be a very stupid question, but I'll try it anyway -- please
> bear with me. [...] I'm probably missing something very obvious --

Don't use the whole supply of flame retardant up front! You never know
when you'll need some in reserve.

Razvan Cojocaru 3
Joined: 2010-07-28,
User offline. Last seen 42 years 45 weeks ago.
Re: wildcard formal parameters

Foreach needs a f(n)

The first block

> {
> print("hello ")
> println(_)
> }

Evaluates to such a function which is n => println (n)

So:
Print done is ran once in the block which builds n => println (n)
This anonymous function is the result of the block (in scala each block returns a value) and is then passed to Foreach which invokes println 5 times.

You have stumbled onto one of the places marked "here be dragons" and I have no rules for you other than "watch your back" when using _ and that the interpreter is your friend.

Thanks,
Razvan

On 2010-11-07, at 1:22 AM, Andy wrote:

> This may be a very stupid question, but I'll try it anyway

Copyright © 2012 École Polytechnique Fédérale de Lausanne (EPFL), Lausanne, Switzerland