Lambda Expressions
In your NyetHack project, create a new file called Narrator.kt to host your narrator and its moods. For now, your narrator will only have one mood: loud. Create a new function called narrate and implement it by defining a lambda expression, calling it, and printing the result:
Listing 8.3 Defining a lambda expression (Narrator.kt
)
fun narrate( message: String ) { println({ val numExclamationPoints = 3 message.uppercase() + "!".repeat(numExclamationPoints) }()) }
Just as you write a string by putting characters between opening and closing quotes, you write a function by putting an expression or statements between opening and closing curly braces. Here, you begin with a call to println. Inside the parentheses ...
Get Kotlin Programming: The Big Nerd Ranch Guide, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.