Reputation: 25816
When I ran the following in the kotlin playground, it prints error, nothing else. What's wrong with the following code? It's pretty simple, I am passing in a function into the data class as one of it's initialization parameters, and then calling this function on the data class instance. Is it not allowed to pass function into a data class in Kotlin?
data class Person(val name: String,
val age: Int = 0,
val showMsg : (msg: String) -> Unit)
fun main(args: Array<String>) {
val p = Person(name="Bob", age=29, {msg -> println(msg)})
p.showMsg("Hello, world!")
}
Upvotes: 3
Views: 3626
Reputation: 147961
A viable alternative to the solutions in the other answers is to pass the last argument lambda outside the parentheses.
If a function takes another function as the last parameter, the lambda expression argument can be passed outside the parenthesized argument list. In this case, you don't need to use a named argument for it:
val p = Person(name = "Bob", age = 29) { println(it) }
Upvotes: 8
Reputation: 2835
You can't use named arguments for 2 of the parameters and ignore the last one (the lambda/function parameter), you just need to name the last parameter as follows.
val p = Person(name="Bob", age=29, showMsg = {msg -> println(msg)})
Upvotes: 3
Reputation: 6793
You cannot mix named and positioned arguments. Use
fun main(args: Array<String>) {
val p = Person(name="Bob", age=29, showMsg = {msg -> println(msg)})
p.showMsg("Hello, world!")
}
or
fun main(args: Array<String>) {
val p = Person("Bob", 29, {msg -> println(msg)})
p.showMsg("Hello, world!")
}
Upvotes: 3
Reputation: 51451
This worked fine for me;
data class Person(val name: String,
val age: Int = 0,
val showMsg : (String) -> Unit
)
val p = Person(name="Bob", age=29, showMsg = ::println)
p.showMsg("Hello, world!")
Upvotes: 3