Yeah, i actually did same thing with stacktraces `...
# announcements
a
Yeah, i actually did same thing with stacktraces
Copy code
private val checkPoints: MutableSet<String> = HashSet()

fun once(action: () -> Unit) {
    val stackTrace = Throwable().stackTrace[1]
    val key = "${stackTrace.fileName}_${stackTrace.methodName}_${stackTrace.lineNumber}"
    if (!checkPoints.contains(key)) {
        checkPoints.add(key)
        action()
    }
}

fun main() {
    repeat(100) {
        once { print("Say hi!") }
    }
}
😱 3
k
Tiny suggestion:
!checkPoints.contains(key)
is
key !in  checkPoints
a
Never check before adding a value, that's doing double work,
add
returns a boolean https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-mutable-set/add.html.
Copy code
if (checkPoints.add(key)) {
    action()
}
r
not that I'd recommend using it anywhere except for debug stuff, but
Thread.currentThread().stackTrace
can give you current stacktrace without creation a Throwable