HelloCW
HelloCW

Reputation: 2255

How can I assign a null lambda (String) -> Unit to a variable directly?

I'm studying Code A. I hope to directly assisn a null lambda expression to onValueChange for test.

But Code B, Code C and Code D are all wrong, how can I assign a null lambda (String) -> Unit to the variable onValueChange ?

Code A

@Composable
fun HelloContent(name2: String, onNameChange: (String) -> Unit) {
    Column(modifier = Modifier.padding(16.dp)) {
        ...
        OutlinedTextField(
            ...
            onValueChange = onNameChange          
        )
    }
}

Code B

@Composable
fun HelloContent(name2: String, onNameChange: (String) -> Unit) {
    Column(modifier = Modifier.padding(16.dp)) {
        ...
        OutlinedTextField(
            ...
            onValueChange = { }
        )
    }
}

Code C

@Composable
fun HelloContent(name2: String, onNameChange: (String) -> Unit) {
    Column(modifier = Modifier.padding(16.dp)) {
        ...
        OutlinedTextField(
            ...
            onValueChange = null           
        )
    }
}

Code D

@Composable
fun HelloContent(name2: String, onNameChange: (String) -> Unit) {
    Column(modifier = Modifier.padding(16.dp)) {
        ...
        OutlinedTextField(
            ...
            onValueChange = fun(x:String):Unit{ }           
        )
    }
}

Upvotes: 0

Views: 507

Answers (1)

Alexey Romanov
Alexey Romanov

Reputation: 170723

You don't say where OutlinedTextField comes from, but I'm guessing this one. In which case the answer is that you can't; the type is (String) -> Unit which is not nullable. And yes, I see parameters like label: () -> Unit = null, but this doesn't make sense; not only is null not a valid parameter, but how would a () -> Unit be interpreted as a label?

But a do-nothing lambda is as in your B and D.

Upvotes: 1

Related Questions