Hello! Is it considered bad practice to define extension functions for native types, such as
String
?
Example, putting a function like this globally scoped in like a
StringUtils.kt
class:
Copy code
fun String.getLinkIfPresent(): String? {
val m: Matcher = urlPattern.matcher(this)
if (m.find()) {
return m.group().trim()
}
return null
}
c
Casey Brooks
05/28/2020, 11:15 PM
Personally, I see no issue with extensions on
String
. Being one of the most-used and most-flexible classes, it makes sense to wrap common String use-cases into an extension.
Extensions on number or boolean types feels a bit more dirty to me
Casey Brooks
05/28/2020, 11:16 PM
I’d probably avoid extensions on numbers or booleans in a library, but they might make more sense in application code, where there might be more of a business-logic reason for it
j
Jakub
05/28/2020, 11:19 PM
Extensions are fine. Depends on a use case. In my opinion in general I would rather avoid extensions that adds logic, it should be more like utilities.
If seems like your extension is using local or global variable
urlPattern
. This may lead to Singletons which are bad practice.