(1.1 only) Var can be val: correct handling of delegated local variables #KT-14409 Fixed

This commit is contained in:
Mikhail Glukhikh
2016-10-25 15:15:35 +03:00
parent 66f3e266d9
commit ba0e36cdb1
4 changed files with 31 additions and 3 deletions
@@ -49,7 +49,10 @@ class CanBeValInspection : AbstractKotlinInspection() {
when (declaration) {
is KtProperty -> {
if (declaration.isVar && declaration.isLocal && canBeVal(declaration, declaration.hasInitializer(), listOf(declaration))) {
if (declaration.isVar && declaration.isLocal &&
canBeVal(declaration,
declaration.hasInitializer() || declaration.hasDelegateExpression(),
listOf(declaration))) {
reportCanBeVal(declaration)
}
}
@@ -63,13 +66,17 @@ class CanBeValInspection : AbstractKotlinInspection() {
}
}
private fun canBeVal(declaration: KtVariableDeclaration, hasInitializer: Boolean, allDeclarations: Collection<KtVariableDeclaration>): Boolean {
private fun canBeVal(
declaration: KtVariableDeclaration,
hasInitializerOrDelegate: Boolean,
allDeclarations: Collection<KtVariableDeclaration>
): Boolean {
if (allDeclarations.all { ReferencesSearch.search(it, it.useScope).none() }) {
// do not report for unused var's (otherwise we'll get it highlighted immediately after typing the declaration
return false
}
if (hasInitializer) {
if (hasInitializerOrDelegate) {
val hasWriteUsages = ReferencesSearch.search(declaration, declaration.useScope).any {
(it as? KtSimpleNameReference)?.element?.readWriteAccess(useResolveForReadWrite = true)?.isWrite == true
}
@@ -79,4 +79,13 @@
<problem_class severity="WARNING" attribute_key="WARNING_ATTRIBUTES">Local 'var' is never modified and can be declared as 'val'</problem_class>
<description>Variable is never modified and can be declared immutable using 'val'</description>
</problem>
<problem>
<file>withReadOnlyDelegate.kt</file>
<line>4</line>
<module>light_idea_test_case</module>
<entry_point TYPE="file" FQNAME="withReadOnlyDelegate.kt" />
<problem_class severity="WARNING" attribute_key="WARNING_ATTRIBUTES">Local 'var' is never modified and can be declared as 'val'</problem_class>
<description>Variable is never modified and can be declared immutable using 'val'</description>
</problem>
</problems>
+6
View File
@@ -0,0 +1,6 @@
// WITH_RUNTIME
fun foo() {
var s: String by Delegates.notNull()
s = ""
}
@@ -0,0 +1,6 @@
// WITH_RUNTIME
fun foo() {
var s: String by lazy { "Hello!" }
s.hashCode()
}