Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow secondary constructors to reference CoroutineDispatchers #5227

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Expand Up @@ -13,6 +13,7 @@ import io.gitlab.arturbosch.detekt.api.internal.Configuration
import io.gitlab.arturbosch.detekt.api.internal.RequiresTypeResolution
import io.gitlab.arturbosch.detekt.rules.fqNameOrNull
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.KtConstructorDelegationCall
import org.jetbrains.kotlin.psi.KtParameter
import org.jetbrains.kotlin.psi.KtSimpleNameExpression
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
Expand Down Expand Up @@ -60,7 +61,8 @@ class InjectDispatcher(config: Config) : Rule(config) {
val type = expression.getType(bindingContext) ?: return
val isCoroutineDispatcher = type.fqNameOrNull() == COROUTINE_DISPATCHER_FQCN ||
type.supertypes().any { it.fqNameOrNull() == COROUTINE_DISPATCHER_FQCN }
val isUsedAsParameter = expression.getStrictParentOfType<KtParameter>() != null
val isUsedAsParameter = expression.getStrictParentOfType<KtParameter>() != null ||
expression.getStrictParentOfType<KtConstructorDelegationCall>() != null
if (isCoroutineDispatcher && !isUsedAsParameter) {
report(
CodeSmell(
Expand Down
Expand Up @@ -61,6 +61,19 @@ class InjectDispatcherSpec(val env: KotlinCoreEnvironment) {
assertThat(subject.compileAndLintWithContext(env, code)).isEmpty()
}

@Test
fun `does not report when dispatcher is used as a secondary constructor parameter`() {
val code = """
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
class MyRepository(dispatcher: CoroutineDispatcher) {
constructor() : this(Dispatchers.IO)
}
"""
assertThat(subject.compileAndLintWithContext(env, code)).isEmpty()
}

@Test
fun `does not report when dispatcher is used as a property`() {
val code = """
Expand Down