Created
May 1, 2021 07:33
-
-
Save davidmigloz/7efa4251a7ddac4fa7c6c985f8dcc47f to your computer and use it in GitHub Desktop.
Dart vs Kotlin: synchronous generation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Iterable<int> oddNumbers(int num) sync* { | |
for (int odd = 1; odd / 2 < num; odd += 2) { | |
yield odd; | |
} | |
} | |
void main() { | |
// Synchronous generation function (returns Iterable) | |
oddNumbers(3) | |
.map((num) { | |
print("O:$num"); | |
return num; | |
}) | |
.map((num) => num + 1) | |
.forEach((num) => print("E:$num")); | |
// Result: O:1; E:2; O:3; E:4; O:5; E:6 | |
// Iterable | |
[1, 3, 5] | |
.map((num) { | |
print("O:$num"); | |
return num; | |
}) | |
.map((num) => num + 1) | |
.forEach((num) => print("E:$num")); | |
// Result: O:1; E:2; O:3; E:4; O:5; E:6 | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fun oddNumbers(num: Int): Sequence<Int> { | |
return generateSequence(1) { it + 2 }.take(num) | |
} | |
fun main() { | |
// Sequence | |
oddNumbers(3) | |
.onEach { println("O:$it") } | |
.map { it + 1 } | |
.forEach { println("E:$it") } | |
// Result: O:1; E:2; O:3; E:4; O:5; E:6 | |
// Iterable | |
listOf(1, 3, 5) | |
.onEach { println("O:$it") } | |
.map { it + 1 } | |
.forEach { println("E:$it") } | |
// Result: O:1; E:2; O:3; E:4; O:5; E:6 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment