posted 9 months ago
I will explain how yield in C# works, because I don't have a lot of experience with Kotlin. If Kotlin works the same way, then you have your answer.
In C#, yield is used when you want to return a lazily enumerated sequence. When execution reaches a yield statement, it returns the next element in the sequence.
So yes, yield is like return in that execution of the function is suspended, and a value is returned. However, yield is different in the following two ways:
yield returns a single element of the sequence, whereas return would return the entire sequence,when the next element of the sequence is needed, execution of the function continues from the last yield,
The base case of your recursive call yields an element, but it doesn't cause your recursive call to unwind, because when the next element is needed, execution continues after the yield statement. In your second snippet, that means the inner for-loop is executed even if parts <= 1.
Again, I don't know Kotlin well enough to be certain that this will work, but in your second code snippet, try adding an empty return after your yield.