androidkotlinunreachable-code

Warning: Unreachable code, Unused equals expression in Kotlin


Here is my code, I don't like warnings. currentFlag.inc() is making warning: unreachable code, if(currentFlag == 1) is making warning: unused equals expression

private fun processGather() {
        TODO("process Gather implemented")
        currentFlag.inc() 

        if (currentFlag == 1) { 
            this.binding.ivStep1.setImageDrawable(AppCompatResources.getDrawable(this, R.drawable.step2))
        } 
    }

Solution

  • You might be misusing TODO. TODO does this:

    Always throws NotImplementedError stating that operation is not implemented.

    It is intended to be used as a placeholder return value for functions that you haven't implemented yet. It seems like in your case, a // TODO comment is more suitable.

    If you actually intend to throw NotImplementedError there, and still want to silence the warning, you can apply the Suppress annotation to the file or to the surrounding method:

    @file:Suppress("UNREACHABLE_CODE", "UnusedEquals")
    // or
    @Suppress("UNREACHABLE_CODE", "UnusedEquals")
    private fun processGather() {
    

    Note that the return type of TODO is Nothing, this tells that the compiler that it will never return (it will always throw an exception). Because of this, it can be analysed that everything after the TODO call will not be executed. Hence, "unreachable code".

    Possibly because of this unreachable code, it also causes the "unused equality expression" inspection to trigger, with the reasoning of "since it's not reachable, it's not used". This might also be unintended, because in my opinion, only the unreachable code inspection should trigger.