0

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{ }           
        )
    }
}
HelloCW
  • 843
  • 22
  • 125
  • 310
  • What's wrong with B and D? – Alexey Romanov Sep 18 '21 at 10:22
  • Compile error: Parameter 'onNameChange' is never used – HelloCW Sep 18 '21 at 10:44
  • But that's not a problem with what you pass to `onValueChange`; just remove the `onNameChange` parameter, use it somewhere, or suppress the diagnostic as shown [here](https://stackoverflow.com/questions/29046636/mark-unused-parameters-in-kotlin). – Alexey Romanov Sep 18 '21 at 10:48
  • Also, for future reference, please always include compile errors, exception stack traces or so on in the question. From the snippets you give it's impossible to tell `onNameChange` isn't used. – Alexey Romanov Sep 18 '21 at 10:50

1 Answers1

1

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.

Alexey Romanov
  • 167,066
  • 35
  • 309
  • 487