Single Argument to one-line Function Literals

26 views
Skip to first unread message

archsky

unread,
Oct 7, 2015, 10:46:43 AM10/7/15
to scala-user
From the Programming in Scala eBook page 78

args.foreach(arg => println(arg))

If a function literal consists of one statement that takes a single argument, you need not explicitly name and specify the argument. Thus, the following code also works:

args.foreach(println)


Good. Now on page 88, thrill is a list, scala REPL says: thrill: List[String] = List(WILL, FILL, UNTIL)

thrill.count(s => s.length == 4)

Now, here, inside the parentheses, it is a function literal, and to me it seems that it contains a single statement, i.e., (according to my current understanding of single statement) something in one line (and that without semi-colons) and the argument for this function literal is also one, i.e., 's'

I tried to apply the former approach, to eliminate the 's' in the latter example.

scala> thrill.count(length == 4)

With the response

<console>:12: error: not found: value length
       thrill.count(length == 4)
                    ^

What is amiss here?

Dennis Haupt

unread,
Oct 7, 2015, 10:53:22 AM10/7/15
to archsky, scala-user
thrill.count(length == 4)
-> compiler does not know what to call "length" on. it checks if there is a def or val called length with zero parameters and does not find any
 
thrill.count(_.length == 4)
-> _ represents the function argument
 
 
 
 
Gesendet: Mittwoch, 07. Oktober 2015 um 16:42 Uhr
Von: archsky <luna...@gmail.com>
An: scala-user <scala...@googlegroups.com>
Betreff: [scala-user] Single Argument to one-line Function Literals
--
You received this message because you are subscribed to the Google Groups "scala-user" group.
To unsubscribe from this group and stop receiving emails from it, send an email to scala-user+...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Dennis Haupt

unread,
Oct 7, 2015, 10:54:02 AM10/7/15
to archsky, scala-user
thrill.count(length == 4)
-> compiler does not know what to call "length" on. it checks if there is a def or val called length with zero parameters and does not find any
 
thrill.count(_.length == 4)
-> _ represents the function argument
Gesendet: Mittwoch, 07. Oktober 2015 um 16:42 Uhr
Von: archsky <luna...@gmail.com>
An: scala-user <scala...@googlegroups.com>
Betreff: [scala-user] Single Argument to one-line Function Literals
--
Reply all
Reply to author
Forward
0 new messages