I have the following code ``` private const...
# announcements
n
I have the following code
Copy code
private const val TIME_OUT = 10000 // in milliseconds
        private val config = RequestConfig.custom()
            .setConnectTimeout(TIME_OUT)
            .setConnectionRequestTimeout(TIME_OUT)
            .setSocketTimeout(TIME_OUT)
            .build()
I only need
TIME_OUT
for this initialization. How can I avoid having it hanging around? One idea I had was
Copy code
private val config = 10_000.let { timeOut ->
            RequestConfig.custom()
                .setConnectTimeout(timeOut)
                .setConnectionRequestTimeout(timeOut)
                .setSocketTimeout(timeOut)
                .build()
        }
but that is not pretty either. Are there better ways?
n
Depends what you mean by "hanging around"
if you want to limit the scope a simpler way to do it is via a run block
Copy code
private val config = run {
        const val TIME_OUT = 10000 
             RequestConfig.custom()
            .setConnectTimeout(TIME_OUT)
            .setConnectionRequestTimeout(TIME_OUT)
            .setSocketTimeout(TIME_OUT)
            .build()
         }
c
If you check the bytecode, the compiler will already optimize this - instead of storing 10000 in a variable, it will simply push the value directly whenever you use the TIME_OUT reference
n
I assumed that they cared more about not having the variable accessible or otherwise coding style, not performance
n
yes, I was only worried about polluting the scope.
run
looks better than my
let
. Thx!
n
np
it's a good trick generally; using a run to avoid things leaking scope. It can also be a good trick when you need to mutate something at an earlier stage but not afterwards, you can create a mutablelist, process it, return it from your run block as a List
n
or use e.g.
buildList
j
My immediate reaction was that it was the type of the constant that was a problem. Its defined as a long! You need a comment to explain the unit! However it represents a duration, so why isn't it a Duration? For me this would be a much more valuable refactoring. Just goes to show how people see different things as important in code 🤔
👍 1
Also are you sure that you want these values to be the same? Does your app have the right behaviour under poor network conditions?
n
duration: yes, code actually uses
10.seconds.toLongNanoSeconds()
and it is a mockup service, so 10 seconds for everything is ok here. I share your overall view on what is important, but really was just trying to improve my low-level coding toolset here.