Skip to content

Commit 384edc5

Browse files
committed
Add a warning for applying a scope on a generated component function or
property as it will have no effect. It should be placed on a @provides function or @Inject constructor instead. Note: due to the limitation with the KAPT back-end it will miss cases where the property is annotated itself instead of it's getter. ex: `@MyScope abstract val myProp` is missed but `@get:MyScope abstract val myProp` is caught. This can be improved once the KAPT back-end is removed. Partially addresses #238
1 parent bd5c4ad commit 384edc5

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed

kotlin-inject-compiler/core/src/main/kotlin/me/tatarka/inject/compiler/TypeCollector.kt

+8
Original file line numberDiff line numberDiff line change
@@ -297,6 +297,14 @@ class TypeCollector(private val provider: AstProvider, private val options: Opti
297297
}
298298
}
299299
if (method.isProvider()) {
300+
val scope = method.scopeType(options)
301+
if (scope != null) {
302+
provider.warn(
303+
"Scope: @${scope.simpleName} has no effect." +
304+
" Place on @Provides function or @Inject constructor instead.",
305+
method
306+
)
307+
}
300308
providerMethods.add(method)
301309
}
302310
}

kotlin-inject-compiler/test/src/test/kotlin/me/tatarka/inject/test/WarningTest.kt

+36
Original file line numberDiff line numberDiff line change
@@ -61,4 +61,40 @@ class WarningTest {
6161
contains("Annotate the following with @Assisted: [assisted: String]")
6262
}
6363
}
64+
65+
@ParameterizedTest
66+
@EnumSource(Target::class)
67+
fun warns_on_scope_on_provider_method_which_is_ignored(target: Target) {
68+
val projectCompiler = ProjectCompiler(target, workingDir)
69+
70+
assertThat(
71+
projectCompiler.source(
72+
"MyComponent.kt",
73+
"""
74+
import me.tatarka.inject.annotations.Component
75+
import me.tatarka.inject.annotations.Scope
76+
import me.tatarka.inject.annotations.Inject
77+
import me.tatarka.inject.annotations.Provides
78+
79+
@Scope annotation class MyScope1
80+
@Scope annotation class MyScope2
81+
82+
@MyScope1 @Component abstract class MyComponent1 {
83+
@get:MyScope1 abstract val foo: String
84+
85+
@Provides fun str(): String = ""
86+
}
87+
88+
@MyScope2 @Component abstract class MyComponent2 {
89+
@MyScope2 abstract fun bar(): String
90+
91+
@Provides fun str(): String = ""
92+
}
93+
""".trimIndent()
94+
).compile()
95+
).warnings().all {
96+
contains("Scope: @MyScope1 has no effect. Place on @Provides function or @Inject constructor instead.")
97+
contains("Scope: @MyScope2 has no effect. Place on @Provides function or @Inject constructor instead.")
98+
}
99+
}
64100
}

0 commit comments

Comments
 (0)