Kotlin: Неразрешенный локальный класс при использовании BroadcastReceiver в действии

Время от времени при компиляции проекта я получаю эту ошибку:

Error:java.lang.UnsupportedOperationException: Unresolved local class: com/myproject/activities/BaseActivity$broadcastReceiver$1
    at org.jetbrains.kotlin.descriptors.NotFoundClasses$classes$1.invoke(NotFoundClasses.kt:44)
    at org.jetbrains.kotlin.descriptors.NotFoundClasses$classes$1.invoke(NotFoundClasses.kt:32)
    at org.jetbrains.kotlin.storage.LockBasedStorageManager$MapBasedMemoizedFunction.invoke(LockBasedStorageManager.java:408)
    at org.jetbrains.kotlin.storage.LockBasedStorageManager$MapBasedMemoizedFunctionToNotNull.invoke(LockBasedStorageManager.java:483)
    at org.jetbrains.kotlin.descriptors.NotFoundClasses.getClass(NotFoundClasses.kt:101)
    at org.jetbrains.kotlin.serialization.deserialization.TypeDeserializer$typeConstructor$1.invoke(TypeDeserializer.kt:120)
    at org.jetbrains.kotlin.serialization.deserialization.TypeDeserializer.typeConstructor(TypeDeserializer.kt:124)
    at org.jetbrains.kotlin.serialization.deserialization.TypeDeserializer.simpleType(TypeDeserializer.kt:82)
    at org.jetbrains.kotlin.serialization.deserialization.TypeDeserializer.type(TypeDeserializer.kt:70)
    at org.jetbrains.kotlin.serialization.deserialization.TypeDeserializer.type$default(TypeDeserializer.kt:62)
    at org.jetbrains.kotlin.serialization.deserialization.MemberDeserializer.loadProperty(MemberDeserializer.kt:67)
    at org.jetbrains.kotlin.serialization.deserialization.descriptors.DeserializedMemberScope.computeProperties(DeserializedMemberScope.kt:123)
    at org.jetbrains.kotlin.serialization.deserialization.descriptors.DeserializedMemberScope.access$computeProperties(DeserializedMemberScope.kt:35)
    at org.jetbrains.kotlin.serialization.deserialization.descriptors.DeserializedMemberScope$properties$1.invoke(DeserializedMemberScope.kt:61)
    at org.jetbrains.kotlin.serialization.deserialization.descriptors.DeserializedMemberScope$properties$1.invoke(DeserializedMemberScope.kt:35)
    at org.jetbrains.kotlin.storage.LockBasedStorageManager$MapBasedMemoizedFunction.invoke(LockBasedStorageManager.java:408)
    at org.jetbrains.kotlin.storage.LockBasedStorageManager$MapBasedMemoizedFunctionToNotNull.invoke(LockBasedStorageManager.java:483)
    at org.jetbrains.kotlin.serialization.deserialization.descriptors.DeserializedMemberScope.getContributedVariables(DeserializedMemberScope.kt:137)
    at org.jetbrains.kotlin.serialization.deserialization.descriptors.DeserializedClassDescriptor$DeserializedClassMemberScope.getContributedVariables(DeserializedClassDescriptor.kt:232)
    at org.jetbrains.kotlin.serialization.deserialization.descriptors.DeserializedClassDescriptor$DeserializedClassMemberScope.computeNonDeclaredProperties(DeserializedClassDescriptor.kt:252)
    at org.jetbrains.kotlin.serialization.deserialization.descriptors.DeserializedMemberScope.computeProperties(DeserializedMemberScope.kt:124)
    at org.jetbrains.kotlin.serialization.deserialization.descriptors.DeserializedMemberScope.access$computeProperties(DeserializedMemberScope.kt:35)
    at org.jetbrains.kotlin.serialization.deserialization.descriptors.DeserializedMemberScope$properties$1.invoke(DeserializedMemberScope.kt:61)
    at org.jetbrains.kotlin.serialization.deserialization.descriptors.DeserializedMemberScope$properties$1.invoke(DeserializedMemberScope.kt:35)
    at org.jetbrains.kotlin.storage.LockBasedStorageManager$MapBasedMemoizedFunction.invoke(LockBasedStorageManager.java:408)
    at org.jetbrains.kotlin.storage.LockBasedStorageManager$MapBasedMemoizedFunctionToNotNull.invoke(LockBasedStorageManager.java:483)
    at org.jetbrains.kotlin.serialization.deserialization.descriptors.DeserializedMemberScope.getContributedVariables(DeserializedMemberScope.kt:137)
    at org.jetbrains.kotlin.serialization.deserialization.descriptors.DeserializedClassDescriptor$DeserializedClassMemberScope.getContributedVariables(DeserializedClassDescriptor.kt:232)
    at org.jetbrains.kotlin.serialization.deserialization.descriptors.DeserializedMemberScope.addFunctionsAndProperties(DeserializedMemberScope.kt:185)
    at org.jetbrains.kotlin.serialization.deserialization.descriptors.DeserializedMemberScope.computeDescriptors(DeserializedMemberScope.kt:153)
    at org.jetbrains.kotlin.serialization.deserialization.descriptors.DeserializedClassDescriptor$DeserializedClassMemberScope$allDescriptors$1.invoke(DeserializedClassDescriptor.kt:218)
    at org.jetbrains.kotlin.serialization.deserialization.descriptors.DeserializedClassDescriptor$DeserializedClassMemberScope$allDescriptors$1.invoke(DeserializedClassDescriptor.kt:211)
    at org.jetbrains.kotlin.storage.LockBasedStorageManager$LockBasedLazyValue.invoke(LockBasedStorageManager.java:323)
    at org.jetbrains.kotlin.storage.LockBasedStorageManager$LockBasedNotNullLazyValue.invoke(LockBasedStorageManager.java:370)
    at org.jetbrains.kotlin.serialization.deserialization.descriptors.DeserializedClassDescriptor$DeserializedClassMemberScope.getContributedDescriptors(DeserializedClassDescriptor.kt:223)
    at org.jetbrains.kotlin.resolve.scopes.ResolutionScope$DefaultImpls.getContributedDescriptors$default(ResolutionScope.kt:40)
    at org.jetbrains.kotlin.resolve.lazy.descriptors.LazyClassMemberScope.computeExtraDescriptors(LazyClassMemberScope.kt:71)
    at org.jetbrains.kotlin.resolve.lazy.descriptors.LazyClassMemberScope$extraDescriptors$1.invoke(LazyClassMemberScope.kt:58)
    at org.jetbrains.kotlin.resolve.lazy.descriptors.LazyClassMemberScope$extraDescriptors$1.invoke(LazyClassMemberScope.kt:47)
    at org.jetbrains.kotlin.storage.LockBasedStorageManager$LockBasedLazyValue.invoke(LockBasedStorageManager.java:323)
    at org.jetbrains.kotlin.storage.LockBasedStorageManager$LockBasedNotNullLazyValue.invoke(LockBasedStorageManager.java:370)
    at org.jetbrains.kotlin.resolve.lazy.descriptors.LazyClassMemberScope.getContributedDescriptors(LazyClassMemberScope.kt:64)
    at org.jetbrains.kotlin.resolve.DescriptorUtils.getAllDescriptors(DescriptorUtils.java:578)
    at org.jetbrains.kotlin.resolve.lazy.descriptors.LazyClassDescriptor.resolveMemberHeaders(LazyClassDescriptor.java:569)
    at org.jetbrains.kotlin.resolve.lazy.descriptors.LazyClassDescriptor.doForceResolveAllContents(LazyClassDescriptor.java:539)
    at org.jetbrains.kotlin.resolve.lazy.descriptors.LazyClassDescriptor.lambda$new$4(LazyClassDescriptor.java:229)
    at org.jetbrains.kotlin.storage.LockBasedStorageManager$LockBasedLazyValue.invoke(LockBasedStorageManager.java:323)
    at org.jetbrains.kotlin.resolve.lazy.descriptors.LazyClassDescriptor.forceResolveAllContents(LazyClassDescriptor.java:535)
    at org.jetbrains.kotlin.resolve.lazy.ForceResolveUtil.doForceResolveAllContents(ForceResolveUtil.java:75)
    at org.jetbrains.kotlin.resolve.lazy.ForceResolveUtil.forceResolveAllContents(ForceResolveUtil.java:41)
    at org.jetbrains.kotlin.resolve.jvm.extensions.PartialAnalysisHandlerExtension$doAnalysis$1.invoke(PartialAnalysisHandlerExtension.kt:66)
    at org.jetbrains.kotlin.resolve.jvm.extensions.PartialAnalysisHandlerExtension$doAnalysis$1.invoke(PartialAnalysisHandlerExtension.kt:34)
    at org.jetbrains.kotlin.resolve.jvm.extensions.PartialAnalysisHandlerExtension.doForEachDeclaration(PartialAnalysisHandlerExtension.kt:119)
    at org.jetbrains.kotlin.resolve.jvm.extensions.PartialAnalysisHandlerExtension.doForEachDeclaration(PartialAnalysisHandlerExtension.kt:133)
    at org.jetbrains.kotlin.resolve.jvm.extensions.PartialAnalysisHandlerExtension.doAnalysis(PartialAnalysisHandlerExtension.kt:61)
    at org.jetbrains.kotlin.kapt3.AbstractKapt3Extension.doAnalysis(Kapt3Extension.kt:145)
    at org.jetbrains.kotlin.cli.jvm.compiler.TopDownAnalyzerFacadeForJVM.analyzeFilesWithJavaIntegration(TopDownAnalyzerFacadeForJVM.kt:104)
    at org.jetbrains.kotlin.cli.jvm.compiler.TopDownAnalyzerFacadeForJVM.analyzeFilesWithJavaIntegration$default(TopDownAnalyzerFacadeForJVM.kt:83)
    at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler$analyze$1.invoke(KotlinToJVMBytecodeCompiler.kt:376)
    at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler$analyze$1.invoke(KotlinToJVMBytecodeCompiler.kt:67)
    at org.jetbrains.kotlin.cli.common.messages.AnalyzerWithCompilerReport.analyzeAndReport(AnalyzerWithCompilerReport.kt:96)
    at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler.analyze(KotlinToJVMBytecodeCompiler.kt:367)
    at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler.compileModules(KotlinToJVMBytecodeCompiler.kt:132)
    at org.jetbrains.kotlin.cli.jvm.K2JVMCompiler.doExecute(K2JVMCompiler.kt:158)
    at org.jetbrains.kotlin.cli.jvm.K2JVMCompiler.doExecute(K2JVMCompiler.kt:61)
    at org.jetbrains.kotlin.cli.common.CLICompiler.execImpl(CLICompiler.java:107)
    at org.jetbrains.kotlin.cli.common.CLICompiler.execImpl(CLICompiler.java:51)
    at org.jetbrains.kotlin.cli.common.CLITool.exec(CLITool.kt:92)
    at org.jetbrains.kotlin.incremental.IncrementalJvmCompilerRunner.runCompiler(IncrementalJvmCompilerRunner.kt:353)
    at org.jetbrains.kotlin.incremental.IncrementalJvmCompilerRunner.runCompiler(IncrementalJvmCompilerRunner.kt:86)
    at org.jetbrains.kotlin.incremental.IncrementalCompilerRunner.compileIncrementally(IncrementalCompilerRunner.kt:213)
    at org.jetbrains.kotlin.incremental.IncrementalCompilerRunner.compile(IncrementalCompilerRunner.kt:83)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl.execIncrementalCompiler(CompileServiceImpl.kt:515)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl.access$execIncrementalCompiler(CompileServiceImpl.kt:96)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl$compile$$inlined$ifAlive$lambda$2.invoke(CompileServiceImpl.kt:399)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl$compile$$inlined$ifAlive$lambda$2.invoke(CompileServiceImpl.kt:96)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl$doCompile$$inlined$ifAlive$lambda$2.invoke(CompileServiceImpl.kt:892)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl$doCompile$$inlined$ifAlive$lambda$2.invoke(CompileServiceImpl.kt:96)
    at org.jetbrains.kotlin.daemon.common.DummyProfiler.withMeasure(PerfUtils.kt:137)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl.checkedCompile(CompileServiceImpl.kt:919)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl.doCompile(CompileServiceImpl.kt:891)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl.compile(CompileServiceImpl.kt:398)
    at sun.reflect.GeneratedMethodAccessor100.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:346)
    at sun.rmi.transport.Transport$1.run(Transport.java:200)
    at sun.rmi.transport.Transport$1.run(Transport.java:197)
    at java.security.AccessController.doPrivileged(Native Method)
    at sun.rmi.transport.Transport.serviceCall(Transport.java:196)
    at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:568)
    at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:826)
    at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.lambda$run$0(TCPTransport.java:683)
    at java.security.AccessController.doPrivileged(Native Method)
    at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:682)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)

My BaseActivity - это что-то вроде:

abstract class BaseActivity : Activity {

    companion object {
        private const val LOG_TAG = "BaseActivity"
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        LocalBroadcastManager.getInstance(this).registerReceiver(broadcastReceiver,
                IntentFilter(MY_FILTER))
    }

    override fun onStop() {
        super.onStop()
        if(isFinishing){
            LocalBroadcastManager.getInstance(this).unregisterReceiver(broadcastReceiver)
        }
    }

    private val broadcastReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) = when (intent?.action) {
            MY_FILTER -> Log.d(LOG_TAG, "This is my filter!")
            else -> Log.e(LOG_TAG, "Hello action ${intent?.action}")
        }
    }
}

Это решается Clean Project и перестроить.

Тем не менее, я хотел бы понять, почему это происходит и как его предотвратить.


Примечание. Это произошло со мной при использовании отладочного вкуса, который не имеет Proguard или других подобных вещей.

Ответ 1

Исправление состоит в том, чтобы указать точный тип вашей переменной, вывод типа не работает в этом случае по какой-либо причине (вероятно, ошибка Kotlin).

Итак, вместо этого:

private val broadcastReceiver = object : BroadcastReceiver()

Используйте это:

private val broadcastReceiver: BroadcastReceiver = object : BroadcastReceiver()

Ответ 2

Похож на какую-то ошибку, и я думаю, что это должно быть на трекере Kotlin, но я предполагаю, что вы можете исправить его пока, определяя приемник как класс:

abstract class BaseActivity : Activity {

    companion object {
        private const val LOG_TAG = "BaseActivity"
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        LocalBroadcastManager.getInstance(this).registerReceiver(broadcastReceiver,
                IntentFilter(MY_FILTER))
    }

    override fun onStop() {
        super.onStop()
        if(isFinishing){
            LocalBroadcastManager.getInstance(this).unregisterReceiver(broadcastReceiver)
        }
    }

    private val broadcastReceiver = MyBroadcastReceiver()

    inner class MyBroadcastReceiver : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) = when (intent?.action) {
            MY_FILTER -> Log.d(LOG_TAG, "This is my filter!")
            else -> Log.e(LOG_TAG, "Hello action ${intent?.action}")
        }
    }
}

Ответ 3

Для полноты: объявление переменной как protected также работает.

protected val broadcastReceiver = object : BroadcastReceiver()

Я предполагаю, что ничего, кроме private, работает.

Ответ 4

It looks like, you have to specify the same object reference

Use below changes: 

private val broadcastReceiver: BroadcastReceiver = object : BroadcastReceiver()