Quwaysim
Quwaysim

Reputation: 427

Can composable functions call non-composable functions?

I saw the new Jetpack Compose in Android and decided to check it out. I have been trying to understand some basic concepts about composables. My question is: Can composable functions call non-composable functions? I have searched Google to no avail.

Upvotes: 4

Views: 5789

Answers (1)

CommonsWare
CommonsWare

Reputation: 1007584

My question is: Can composable functions call non-composable functions?

Yes. Pretty much everything in Kotlin winds up as a function call, and most functions available to you are non-composable.

Here is one of Google's bits of sample Compose UI code:

@Composable
fun NewsStory() {
    val image = imageResource(R.drawable.header)
    Column(
        modifier = Modifier.padding(16.dp)
    ) {
        val imageModifier = Modifier
            .preferredHeight(180.dp)
            .fillMaxWidth()

        Image(image, modifier = imageModifier,
                  contentScale = ContentScale.Crop)
        Spacer(Modifier.preferredHeight(16.dp))

        Text("A day in Shark Fin Cove")
        Text("Davenport, California")
        Text("December 2018")
    }
}

In that, the following functions are not @Composable:

  • imageResource()
  • Modifier.padding()
  • Modifier.preferredHeight()
  • Modifier.fillMaxWidth()

The rule is that a function marked with @Composable needs to be called by another function marked as @Composable or one of a small family of end consumers of composable functions. This is reminiscent of coroutines, where suspend functions need to be called by other suspend functions or one of a small family of end consumers of suspend functions (e.g., coroutine builders like launch()).

Upvotes: 7

Related Questions