s-hunter
s-hunter

Reputation: 25816

How to pass a function into a data class in Kotlin?

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

Answers (4)

hotkey
hotkey

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

Ahmed Ashraf
Ahmed Ashraf

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

leonardkraemer
leonardkraemer

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

Strelok
Strelok

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

Related Questions