I know it’s more standard to put `Density` as the ...
# codereview
m
I know it’s more standard to put
Density
as the receiver, but isn’t the API usage cleaner when doing this?
Copy code
fun TextUnit.scale(scale: Float, density: Density): TextUnit {
    if (this.isUnspecified) return this
    return with(density) {
        (scale * this@scale.toPx()).toSp()
    }
}
e
I don't think so. for most places where you'd be likely to need such conversion,
Density
is some outer
this
scope, which means you'd have to explicitly qualify
this@Layout
in order to use it with that function
z
Maybe you’re wishing for context parameters?
👍 1
m
@Zach Klippenstein (he/him) [MOD] I haven’t used context receivers before and now I see they are replaced by context parameters, as you say. For the old way, I guess this would work:
Copy code
context(Density)
fun TextUnit.scale(scale: Float): TextUnit {
    if (this.isUnspecified) return this
    return (scale * this@scale.toPx()).toSp()
}
Are context parameters supported by kotlin 2.0.21? @ephemient my app might be a little odd, but in all the places I call this function, the density is only retrieved/passed for this call, so I pass it by name (e.g.
density
). However, it does seem more consistent to use the context receiver/parameter so that
scale
is called in the same way as
toSp()
etc.
c
The very first experimental version of context parameters will be in Kotlin 2.2 but it's not clear yet whether that will include IntelliJ support or not.
thank you color 1
e
actually now that I see what you're trying to do - why do you even need
.toPx().toSp()
?
Copy code
fun TextUnit.scale(scale: Float): TextUnit = this * scale
(or don't even have the function at all, just use
*
or
.times()
)
m
https://developer.android.com/about/versions/14/features#non-linear-font-scaling which states:
Copy code
Avoid hardcoding equations using Configuration.fontScale or DisplayMetrics.scaledDensity. Because font scaling is nonlinear, the scaledDensity field is no longer accurate. The fontScale field should be used for informational purposes only because fonts are no longer scaled with a single scalar value.
For example, if the device font size is set to be the max level, then a large font size will not be much larger (rendered size) than a font size with half the value. So if some text measures as 200px and you want to fit it into 100px, then halving the font size will not work (unless the device is set to use default font scaling). It’s a super-easy mistake to make when manipulating font sizes in order to fit text.