aryaxt
aryaxt

Reputation: 77596

Kotlin recursive problem when type checking

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

Upvotes: 2

Views: 3202

Answers (1)

Amin
Amin

Reputation: 3186

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
        }
   }
}

Upvotes: 3

Related Questions