In my Android code, I find I have this Kotlin styl...
# android
s
In my Android code, I find I have this Kotlin style issue a lot. What do you guys do?
Copy code
val example: List<String> = when (example) {
            // ...
        }
            .doSomethingAfter()
I really feel like the
.doSomethineAfter()
is misplaced and is ugly. Is there a solution to this that I'm not aware of?
d
Doesn't exactly answer your question on formatting that exact code but the easiest way I have found is to lift the
when
expression out into a val:
Copy code
val firstThing = when (example) { ... }
 
val result = firstThing.doSomethingAfter()
Especially helps readability when
firstThing
can be named something semantically meaningful
ℹ️ 1
s
yes, is doable, but I don't like doing this much either as it creates a temporary variable in my algorithm that is unnecessary and isn't used anywhere else. Maybe I'm being too particular, but in my algorithms I like to only pollute the global namespace of the function with necessary things
c
One could look at if from the perspective of the extra variable being “necessary” to clarify the intent for readers of the code (even though it isn’t necessary for the algorithm).
👍 3
1
s
maybe you are right
c
it’s always a balancing act - structuring the code to be nice to “Future You” versus code that has mechanical sympathy for the runtime.
💯 3
d
I'd always optimise for code readability over performance where I can. Certain applications might need to be ultra performant but for me that's usually secondary to maintainability
❤️ 1
👍 1
m
As a suggestion, to keep the functional style and prevent declaring a new variable in your algorithm you could use the
let
function.
Copy code
val result = when (example) {
    //...
}.let { firstThing ->
    firstThing.doSomethingAfter()
}
d
Copy code
val result = when(example) {
//....
}.apply { doSomethingAfter() }
👍 1
m
apply
is more suitable if
doSomethingAfter()
doesn't return anything. I assume it returns something after doing the computation. 😀
s
hmmm
that's an idea
👍 1
c
.also
would be idiomatic to also do some other operation, returning a result.
m
Please consider the result of the returned value from these functions in the given context.
Copy code
val a:Int  = listOf("0").let { it.first().toInt() }
val c:List<String>  = listOf("").also { it.first().toInt() }
val b:List<String>  = listOf("").apply { first().toInt() }
c
The Kotlin docs provide guidance on selecting appropriate scope function based on purpose.
👍 1