saveourtool/diktat

`WRONG_NAME_OF_VARIABLE_INSIDE_ACCESSOR` false positive when using property references inside an accessor

Open

#1,464 opened on Jul 20, 2022

View on GitHub
 (0 comments) (0 reactions) (1 assignee)Kotlin (40 forks)github user discovery
buggood first issue

Repository metrics

Stars
 (571 stars)
PR merge metrics
 (PR metrics pending)

Description

Minimal repro

package com.example

interface Interface {
    val state: Int
}

abstract class Primitive : Interface

class Composite : Interface {
    private val primitives = emptyList<Primitive>()

    override val state: Int
        get() =
            42 + primitives.sumOf(Interface::state)
}

Even a smaller repro

package com.example

class Klazz {
    private val children = emptyList<Klazz>()

    val state: Int
        get() =
            42 + children.sumOf(Klazz::state)
}

Observed behavior

file.kt:13:9: [WRONG_NAME_OF_VARIABLE_INSIDE_ACCESSOR] use `field` keyword instead of property name inside property accessors: get() =... (diktat-ruleset:getter-setter-fields)

An additional problem with the above error is that the special field identifier is only allowed when there's a backing field (i. e. the property has been initialized), e. g.:

    val state: Int = 42
        get() {
            println(field)
            return 44
        }

Environment information

  • diktat version: 1.2.2-SNAPSHOT at a17825ae283f3f01eef2c664afea7fdd54eea185

Contributor guide