fun sayHello(greet:String,itemsToGreet:List<String>){
itemsToGreet.forEach { itemsToGreet ->
println("$greet, $itemsToGreet")
}
}
fun main() {
val interestingThings = listOf("kotlin","program","comic")
sayHello(greet="hi", interestingThings)
}
Asked
Active
Viewed 60 times
0

Robby Cornelissen
- 91,784
- 22
- 134
- 156

Saptarshi Ghosh
- 7
- 3
-
3It's hard to help with an error without seeing the original error message. Please edit your post to include the exact wording of any error messages, including the full [stack trace](/a/23353174) of any exceptions, if applicable, as well as which line of code the stack trace points to. Please see [ask] and [How to create a Minimal, Reproducible Example](/help/minimal-reproducible-example) – Ryan M May 06 '20 at 23:38
1 Answers
3
A couple of problems:
- You can't mix named and positional arguments in a method call. This results in a compilation error.
- While not explicitly wrong, the fact that you're shadowing the
itemsToGreet
variable in your lambda expression is a code smell.
This fixes both:
fun sayHello(greet:String,itemsToGreet:List<String>) {
itemsToGreet.forEach { item -> // new variable name
println("$greet, $item")
}
}
fun main() {
val interestingThings = listOf("kotlin", "program", "comic")
sayHello("hi", interestingThings) // positional arguments
sayHello(greet="hi", itemsToGreet=interestingThings) // named arguments
}

Robby Cornelissen
- 91,784
- 22
- 134
- 156