Would a rule checking for this (specifically usages in the form of
users.map { it.name }.toTypedArray()
) fit in detekt's rule sets or is it something that should be kept 3rd party?
e
ephemient
02/07/2024, 5:46 PM
(not a Detekt developer but)
.map
is necessary if it's not a
List
and
.map
is desirable if it's not a
RandomAccessList
, which may be context that even Detekt with type resolution doesn't know
e
eygraber
02/07/2024, 5:47 PM
Ah good point. Maybe it can try and track where the
List
came from, and only raise a violation if it can determine where it came from and that it is a
RandomAccessList
but that seems like a lot
eygraber
02/07/2024, 5:48 PM
It's almost like I ignored the fact that it was called out in the article multiple times though 🙈
e
ephemient
02/07/2024, 5:52 PM
if it were a common pattern in my codebase, I might write a
Copy code
inline fun <T, reified R> Iterable<T>.mapToTypedArray(block: (T) -> R): Array<R> =
if (this is List<T> && this is RandomAccess) {
Array(this.size) { block(this[it]) }
} else {
this.map(block).toTypedArray()
}
and write a rule suggesting that, but I think it comes up pretty rarely so idk
b
Brais Gabin
02/07/2024, 6:48 PM
I think that this rule could go in the performance rule set. In general we are more lean to improve the code readability but I think that a rule like that in detekt would not hurt.
Brais Gabin
02/07/2024, 6:50 PM
I must say that I also prefer a inline function like the one shared by @ephemient than the actual code. That constructor call feels odd.