Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I restrict the type of a parameter in Android Jetpack Compose with Kotlin?

I can use Code A to display a dialog of edit box. In fact, the parameter editTextConten need to accept a variable just like var editContent by remember { mutableStateOf("Hello") } .

How can I restrict a type of parameter ?

BTW, the Code B and Code C are wrong.

Code A

@Composable
fun DisplayEditBox(
    editTextContent:String,
    onChangEditTextContent: (String) ->Unit
) {
    TextField(
        value = editTextContent,
        onValueChange = onChangEditTextContent
    )
}

@Composable
fun ScreenHome_Line() {
    var editContent by remember { mutableStateOf("Hello") }
    DisplayEditBox(editContent) {
        editContent = it
    }
}

Code B

@Composable
fun DisplayEditBox(
    editTextContent:String = remember {mutableStateOf("") },
    onChangEditTextContent: (String) ->Unit
) {
    TextField(
        value = editTextContent,
        onValueChange = onChangEditTextContent
    )
}

Code C

@Composable
fun DisplayEditBox(
    editTextContent:String by remember {mutableStateOf("") },
    onChangEditTextContent: (String) ->Unit
) {
    TextField(
        value = editTextContent,
        onValueChange = onChangEditTextContent
    )
}
like image 831
HelloCW Avatar asked Jan 16 '26 18:01

HelloCW


1 Answers

You can use State<*> as type.

@Composable
fun DisplayEditBox(
    editTextContent: State<String>,
    onChangEditTextContent: (String) -> Unit
) {
    TextField(
        value = editTextContent.value,
        onValueChange = onChangEditTextContent
    )
}

@Composable
fun ScreenHome_Line() {
    val editContent = remember { mutableStateOf("Hello") }
    DisplayEditBox(editContent) {
        editContent.value = it
    }
}

Now you can send only State value as parameter and it will force call site to handle state for your code. And prevent call site to send raw string as parameter.

like image 173
Viacheslav Smityukh Avatar answered Jan 19 '26 19:01

Viacheslav Smityukh