I met a weird `IllegalAccessError` when using ktor...
# ktor
j
I met a weird
IllegalAccessError
when using ktor. I defined a
Controller
interface. A controller can be added to a router. I made a helper method to create a controller that wraps the handler with my exception handling and other logics. A simplified version is
Copy code
interface Controller {
    fun addToRouter(routing: Routing)

    companion object {
        fun handleException(e: Throwable) {
            throw e
        }

        inline fun create(method: HttpMethod, path: String, crossinline handler: suspend () -> Unit): Controller = object : Controller {
            override fun addToRouter(routing: Routing) {
                routing.route(path, method) {
                    handle {
                        try {
                            handler()
                        } catch (e: Throwable) {
                            handleException(e)
                        }
                    }
                }
            }
        }
    }
}
In the
controllers
package, there is a controller with a body that may throw an exception.
Copy code
val errorController = Controller.create(HttpMethod.Get, "/error") {
    throw Exception("This is an error")
}
In the
Routing.kt
, all controllers are added to the routing.
Copy code
routing {
        controller.errorController.addToRouter(this)
        // other controllers
    }
Now when I tried to call the controller, if an exception is thrown, the
IllegalAccessError
is caused.
Copy code
java.lang.IllegalAccessError: class controller.ErrorControllerKt$special$$inlined$create$1$1$1 tried to access field routing.Controller$Companion.$$INSTANCE (controller.ErrorControllerKt$special$$inlined$create$1$1$1 and routing.Controller$Companion are in unnamed module of loader 'app')
Why will it happen?
I know I can fix it by not using
inline
, but I'm curious about the reason.
I asked in another group and they found out that it was likely to be a bug of Kotlin compiler. They are creating the issue.