Home > OS >  Name Shadowing in kotlin
Name Shadowing in kotlin

Time:10-28

Recently, I face this warning in my IntelliJ Idea. But I don't have any solution for that... Also, I don't want to use the @Suppress("NAME_SHADOWING"). I'll be grateful if you guide me. This is my code:

fun add(
    @Parameter id: Long?
): someClass {
    myTable?.content?.firstOrNull { it.add }?.id?.let { id ->
        db.products.readById(id)?.let { db.products.delete(it) }
    }
    return remove(id)
}

CodePudding user response:

Name shadowing means that you are using variables with the same name in different scopes, making it more likely that you by accident refer to the wrong one. The solution is to rename them to be different. In your case it's the variable id. It is both the parameter of the function and it is also defined after the first let. So you could for example do this to remove the warning:

fun add(
    @Parameter id: Long?
): someClass {
    myTable?.content?.firstOrNull { it.add }?.id?.let { id2 ->
        db.products.readById(id2)?.let { db.products.delete(it) }
    }
    return remove(id)
}

CodePudding user response:

fun add(
    @Parameter id: Long?
): someClass {
    myTable?.content?.firstOrNull { it.add }?.id
        ?.let { id ->
            // Here you have two variables named "id" (the other being the function parameter)
            db.products.readById(id)?.let { db.products.delete(it) }
        }
    return remove(id)
}

Simply rename one of the parameters and the warning will go away.

  • Related