Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin recursive problem when type checking

Tags:

android

kotlin

I have the following code which i think is valid, because the recursion happens as a result of a callback. It's not called directly as a result of the function call. But the compiler seems to think there is a recursion issue

class Model(callBack: CallBack) {
    interface CallBack {
        fun onSomething()
    }
}

class SomeClass {
   fun createModel() = Model(callBack)
        
   val callBack = object : Model.CallBack {    
        override fun onSomething() {
            val anotherModel = createModel()
            // Use model for something
        }
   }
}
Type checking has run into a recursive problem. Easiest workaround: specify types of your declarations explicitly

Is there a workaround for this?

EDIT

I also tried changing callBack to a function so that the same instance is not referenced by multiple models, but I get the same error

like image 374
aryaxt Avatar asked Sep 09 '26 00:09

aryaxt


1 Answers

The recursive problem mentioned is not about function calls, it's about the compiler trying to find out the types of the declaration and it has stuck in a recursive type checking. It wants to find the output type of createModel which depends on the type of val callback and it depends on createModel again. As it says, declare their types to fix the issue.

class Model(callBack: CallBack) 
{
    interface CallBack {
        fun onSomething()
    }
}

class SomeClass {
    fun createModel() : Model = Model(callBack)
        
   val callBack : Model.CallBack = object : Model.CallBack {    
        override fun onSomething() {
            val anotherModel : Model = createModel()
            // Use model for something
        }
   }
}
like image 99
Amin Avatar answered Sep 11 '26 18:09

Amin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!