visit
Most of the time we see Extension functions but Kotlin also supports Extension properties.
fun Context.getCompatColor(@ColorRes colorId: Int) = ResourcesCompat.getColor(resources, colorId, null)
fun Context.getCompatDrawable(@DrawableRes drawableId: Int) = AppCompatResources.getDrawable(this, drawableId)!!
// Activity
getCompatColor(R.color.white)
// Fragment
requireContext().getCompatColor(R.color.white)
fun Context.hasPermissions(vararg permissions: String) = permissions.all { permission ->
ContextCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_GRANTED
}
// Traditional way (Activity)
(ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) && (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED)
// Extension (Activity)
hasPermissions(Manifest.permission.CAMERA, Manifest.permission.ACCESS_FINE_LOCATION)
fun Context.copyToClipboard(content: String) {
val clipboardManager = ContextCompat.getSystemService(this, ClipboardManager::class.java)!!
val clip = ClipData.newPlainText("clipboard", content)
clipboardManager.setPrimaryClip(clip)
}
fun Context.isResolvable(intent: Intent) = intent.resolveActivity(packageManager) != null
fun Context.view(uri: Uri, onAppMissing: () -> Unit) {
val intent = Intent(Intent.ACTION_VIEW, uri)
if (!isResolvable(intent)) {
onAppMissing()
return
}
startActivity(intent)
}
// Activity
view(uri, onAppMissing = {
// show error message
})
val isoFormatter = SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS")
fun Date.toISOFormat() : String = isoFormatter.format(this)
Date(52).toISOFormat() // 2021-05-12 23:38:07.540
fun Date.plusDays(days: Int): Date {
return Date(this.time + (days * ONE_DAY_MS))
}
fun Date.plusMillis(millis: Long): Date {
return Date(this.time + millis)
}
fun Any?.isNull() = this == null
if (something.isNull()) { ... }
fun Any?.isNull() = this == null
if (something.isNull()) { ... }
The dangerous thing about this code is that money is not formatted equally worldwide. In some countries you’ll see 1,200.00 (comma first, dot after), in others 1.200,00 (dot first, comma after). This is only a problem if the app is/will be used in many countries.
My solution would be to add the formatting pattern to strings.xml
and create an extension on Context
to handle that. That way you can define the monetary format for each language and still use the same function.
fun Context.formatPrice(price: Double) : String {
val formatter = DecimalFormat(getString(R.string.price_formatter))
return formatter.format(price)
}
val <T> List<T>.lastIndex: Int
get() = size - 1
Cover photo by Fran Jacquier on
Also published .