Advice on refactoring this code snippet


#1

  

fun ServiceProxy.rewriter(configure: RewriteInterceptor.() -> Unit) {
  val interceptor = RewriteInterceptor()
  interceptor.configure()
  getInterceptors().add(interceptor)
}

fun ServiceProxy.request(configure: RequestInterceptor.() -> Unit) {
  val interceptor = RequestInterceptor()

    interceptor.configure()
    getInterceptors().add(interceptor)
}

(RewriteInterceptor and RequestInterceptor implement the same interface.)


#2

I don't know what do you want to achieve with refactoring, but I would probably create "intercept" helper method like this:

fun <T:Interceptor> ServiceProxy.intercept(interceptor: T, configure: T.()->Unit) {   interceptor.configure()   getInterceptors().add(interceptor) }

and use it like this to build DSL

fun ServiceProxy.rewrite(configure: RewriteInterceptor.()->Unit) = intercept(RewriteInterceptor(), configure)

#3

Thanks, exactly what I was looking for.