How to debug Kotlin sequences / collections

Take the following single-line layer, which can be expressed as a series of operations on a set or sequence:

val nums = (10 downTo 1) // .asSequence() if we want this to be a sequence .filter { it % 2 == 0 } .map { it * it } .sorted() // .asList() if declaring it a sequence println(nums) // [4, 16, 36, 64, 100] 

Let's say I want to see elements at every step, they will be (from subtraction):

 [10, 9, 8, 7, 6, 5, 4, 3, 2, 1] [10, 8, 6, 4, 2] [100, 64, 36, 16, 4] [4, 16, 36, 64, 100] 

Unfortunately, there is no good way to debug this using the debugger or to log these values ​​for later verification. With good functional programming constructs, whole methods can be rewritten as single statements like this, but there seems to be no good way to check intermediate states, even count ( 10, 5, 5, 5 here).

What is the best way to debug them?

+6
source share
2 answers

You can register intermediate values ​​(lists) with

 fun <T> T.log(): T { println(this); this } //USAGE: val nums = (10 downTo 1) .filter { it % 2 == 0 }.log() .map { it * it }.log() .sorted().log() 

This will work as desired, as in your example you are working with collections, not sequences. For lazy Sequence you need:

 // coming in 1.1 public fun <T> Sequence<T>.onEach(action: (T) -> Unit): Sequence<T> { return map { action(it) it } } fun <T> Sequence<T>.log() = onEach {print(it)} //USAGE: val nums = (10 downTo 1).asSequance() .filter { it % 2 == 0 } .map { it * it }.log() .sorted() .toList() 
+8
source

In Intellij Idea’s latest idea, when you add a breakpoint, you can set it to not check the whole expression, but only the Lambda body.

enter image description here

Then in the debugging itself you can see what happens inside your lambda.

enter image description here

But this is not the only way. You can also use Run to cursor (Alt + F9) .

+7
source

Source: https://habr.com/ru/post/1014118/


All Articles