https://kotlinlang.org logo
#ktor
Title
# ktor
b

bbaldino

07/09/2020, 5:46 PM
Is there a good pattern to define the application module inside of a class? We use a qualified class name for our loggers, so having just the standalone extension function is a bit awkward. I've done something like this:
Copy code
class MyClass {
    val module: Application.() -> Unit {
        ...
    }
}
and then it's installed/started via something like:
Copy code
val myClass = MyClass()
embeddedServer(Jetty) {
    myClass.module(this)
}
which isn't bad, but wondering if there's a better/more idiomatic way?
n

nschulzke

07/09/2020, 6:42 PM
If there's no state stored in the class (it's just a wrapper for the function), it can be an
object
instead without any worry about shared state. Then you can do this:
Copy code
embeddedServer(Jetty, module=MyClass.module)
b

bbaldino

07/09/2020, 6:44 PM
Hm, that's good to know. Any other way for if there is state?
n

nschulzke

07/09/2020, 6:49 PM
If you do have shared state, I think you probably have as good a method as any, except that I would personally just inline the creation of the object:
Copy code
embeddedServer(Jetty, module=MyClass().module)
b

bbaldino

07/09/2020, 6:50 PM
Yeah I did end up inlining it like that
The state is either some handlers that get invoked or a class that is called into
n

nschulzke

07/09/2020, 6:54 PM
Is the state located inside the
class MyTest
, in the Application itself, or in global variables? If your class only has that single function (the application module), then presumably all state is contained in the receiving Application object, which is fine.
From what you've said, it sounds like all you've done is taken what was a top-level function and moved it into a class all on its own for logging purposes. In that case, all you're really looking for is a handle on that function, which means you don't need to worry about creating new instances of a class every time you want to call it.
b

bbaldino

07/09/2020, 6:57 PM
No not global...basically there's a core class of the app and this is an http API surface for interacting with it. So /startservice, say, calls controller.startservice...the ktor module has to have access to the controller. I know I can pass it as an arg to the extension function (which is what I had) but the logger and other stuff made me think about encapsulating all this in a class.
Yes if I'm understanding you right I think you've summarized it correctly
👍 1
n

nschulzke

07/09/2020, 7:02 PM
It's not a huge commitment either way, so just pick something you like and go with it. Refactoring an object to a class and vice versa isn't terribly complicated, especially for something that occurs so rarely in the code.
b

bbaldino

07/09/2020, 7:12 PM
Yup, true
3 Views