One Off the Slack: A Matter of Units

A question came up that often appears in the course of ordinary Android development, outside of Compose:

why compose uses sp, dp, instead of raw number just like flutter…

The problem is that we have varying screen densities, so we want to use density-independent units wherever possible (dp, sp). Or, as Brian Gardner put it:

I think it’s forcing the use of good patterns. Sizes should be declared in dp units so the sizes are the same on different screen densities. Text needs to be declared in sp units so it also resizes based on density but also takes into account the user’s text accessibility settings. Using a regular number would not support either of these cases

(here, “regular number” presumably refers to just using an integer value like 8 instead of one with the unit applied, like 8.dp)

The Compose syntax of using .dp and .sp extension properties, while being somewhat of a hack from a pure Kotlin syntax standpoint, are very sweet in terms of cognitive overhead. The Dp and Sp classes that we wind up using are Kotlin inline classes, so they add little performance overhead as well.

As Colton Idle points out, Android itself is very inconsistent on what units of measure get used:

As long as I can set things everywhere in dp. Maybe it’s just me, but definitely in the current android toolkit I would do setSomething(sizeInPx) and I had to do the px to dp conversion myself. Which is fine… but it ended up being a util I had to add into every project, when it should have in fact just been handled by the api in my opinion.

Leland Richardson elaborated on that, pointing out that why developer facing APIs should be using Dp and Sp in general, a lot of the Compose internals need to use pixels. And, in some cases, Compose may still be leaking pixels into APIs:

for instance, some gesture events give you pixels which might be annoying if you’re using that value in user-land where dp is the thing you want

But, overall, being intentional about units for dimensions is a vast improvement over what we do in traditional Android development. I’ll echo Romain Guy’s comment: “this is one of my favorite features”.


Read the original thread in the kotlinlang Slack workspace. Not a member? Join that Slack workspace here!