Last active
April 23, 2021 12:53
-
-
Save harsh183/dbdf535dda4a3e00f214ffe211fc7a63 to your computer and use it in GitHub Desktop.
Recreating ruby's n.times operator on Kotlin. This is for fun, in all seriousness use the repeat(n) operator
This file contains 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 main() { | |
// normal function | |
repeat(3) { print("Yay $it ") } | |
// => Yay 0 Yay 1 Yay 2 | |
2.times { print("Looop ") } | |
// => Looop Looop | |
10.times { print("$it ") } | |
// => 0 1 2 3 4 5 6 7 8 9 | |
} | |
// Note: times is already defined as multiplication in Kotlin as well, | |
// I just named it as such to recreate the Ruby syntax | |
infix fun Int.times(fn: (Int) -> Unit) = repeat(this, fn) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It's also trivial to write this without using
repeat
(that's how I initially approached it).