Skip to content

Commit

Permalink
Allow secondary constructors to reference CoroutineDispatchers (#5227)
Browse files Browse the repository at this point in the history
Allow constructor delegation elements to refer to dispatchers
directly, similar to how default parameters are allowed to.

Fixes #5225
  • Loading branch information
josephlbarnett committed Aug 20, 2022
1 parent ebf0b1f commit b8fbc8e
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 1 deletion.
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

0 comments on commit b8fbc8e

Please sign in to comment.