I was recently faced with a task of converting an Int
to a more readable String
value. The Int
that I was working with was from a library, more specifically - Google’s MLKit library. The Int
s in question were Barcode formats (eg. Barcode.FORMAT_QR_CODE, Barcode.FORMAT_PDF417…)
To make life easier I made the following extension function:
fun Int.toFriendlyName(): String {
return when (this) {
is Barcode.FORMAT_QR_CODE -> "Qr Code"
is Barcode.FORMAT_PDF417 -> "PDF417"
else -> "Not supported"
}
}
But I have a problem with this approach - who is to say that a developer won’t misuse this extension function with any Int
?
...
val sillyUsage = 3.toFriendlyName()
...
If I look into the source code (from the MLKit Library) for getting the barcode format, the Java code looks like this:
@Barcode.BarcodeFormat
public int getFormat() {
int var1 = this.zza.zzf();
if (var1 <= 4096) {
if (var1 == 0) {
return -1;
}
} else {
var1 = -1;
}
return var1;
}
Given that there is an annotation (@Barcode.BarcodeFormat
) for the getFormat()
method, would it not be useful to use it in the extension function to limit its usage? For example:
fun @Barcode.BarcodeFormat Int.toFriendlyName(): String {
return when (this) {
is Barcode.FORMAT_QR_CODE -> "Qr Code"
is Barcode.FORMAT_PDF417 -> "PDF417"
else -> "Not supported"
}
}
Of course, the above demonstration might not be syntactically correct… but hopefully the idea that I am proposing still makes sense.
Ideally, this would mean that if a developer then tried
...
val sillyUsage = 3.toFriendlyName()
...
that there would be an IDE warning saying that is not a valid function call.
Looking forward to hearing your thoughts, or even if I have been silly and missed something out.
Thank you in advance