Kotlin: mark function argument after sanitizing it into a new variable as "do not use this anymore"

84 views Asked by At

To start: this question is already kind of resolved for me. But the discussion might be interesting.

I like code so let's look at this function:

    fun foo(path: Path) {
        val absPath = path.normalize().absolute() // sanitizing
        doSomethingWith(path) // this is unsafe use because path is not sanitized
        doSomethingWith(absPath) // this is safe because we are using the sanitized absPath value
    }

Kotlin function parameters are always val, therefore we are required to create a new variable if we want to derive from it's value. We can choose between using a new name or using an old name and annotating it with @Suppress("NAME_SHADOWING") to not get the Name shadowed: ... warning.

I'm looking for something like

    fun foo(path: Path) {
        val absPath = path.normalize().absolute()
        @DoNotUseAnymore path
        doSomethingWith(path) // should give a warning/error
        doSomethingWith(absPath) // is fine
}

Do you know something like that? Or do you think I'm fiddling around at the wrong end of the equation and should just learn to not feel like doing bad stuff when using the @Suppress-annotation? Since I like to code, this is what I mean:

    fun foo(path: Path) {

        @Suppress("NAME_SHADOWING")
        val path = path.normalize().absolute() // sanitizing

        doSomethingWith(path) // there is only one sanitized variable so we are safe
    }

In some way this method is the cleanest one... I probably stick to that... Should I publish this question now? Well... maybe :)

0

There are 0 answers