You might have thought that Kotlin cannot get any better - but now you have found this library.

Overview
____________________________________________________
|     ____  __.      __  .__  .__                  |
|    |    |/ _|_____/  |_|  | |__| ____   07/2016  |
|    |      / /  _ \   __\  | |  |/    \           |
|    |    | \(  (_} )  | |  |_|  |   |  \          |
|    |____|__ \____/|__| |____/__|___|  /          |
|            \/                       \/           |
|            __  .__                               |
|          _/  |_|__| _____   ____   ______        |
|          \   __\  |/     \_/ __ \ /  ___/        |
|           |  | |  |  Y Y  \  ___/ \___ \         |
|           |__| |__|__|_|  /\___  >____  )        |
|                         \/     \/     \/         |
|                                                  |
|           -  -  BREAKING NEWS!  -  -             |
|   A software engineering masterpiece released!   |
|  ___________________________                     |
|  | fun thisReallyWorks() { | "Kotlin  literally  |
|  |   50 times {            | becomes    another  |
|  |     println("""         | language",    said  |
|  |                         | some random Kotlin  |
|  |    This would print     | developer.   After  |
|  |                         | many long years of  |
|  |   oooooooo   .oooo.     | careful    coding,  |
|  |  dP"````"P  d8P'`Y8b    | kotlin-times  says  |
|  | d88888b.   888    888   | goodbye to the lab  |
|  |     `Y88b  888    888   | and  finally  sees  |
|  |       ]88  888    888   | the  light of day.  |
|  | o.   .88P  `88b  d88'   | "Pure awesomeness", |
|  | '8bd88P"    `Y8bd8P'    | said the other guy. |
|  |                         |      -  -  -        /
|  |                times!   |   More info and    /
|  |     """)                |    poor quality   /
|  |   }                     |  screen captures /
|  | }                       |    on page 42.  /
|  |_________________________|              /\/
\                                          /
 \  /\   In other news: Java still verbose/
  \/  \/\    /\  /\/\  /\/\  /\/\    /\  /
         \  /  \/    \/    \/    \  /  \/
          \/                      \/

Maven Central Just kidding Kotlin

You might have thought that Kotlin cannot get any better - but now you have found this library. Thanks to kotlin-times your Kotlin applications will never be the same. Enter the future of programming.

Kotlin Times

This library, carefully crafted by our Kotlin experts, extends Byte, Short, Int and Long types with infix methods sharing times identifier. It effectively allows its users to set up simple and readable loops with a pleasant Kotlin*-ish* syntax:

50 times {
  println("Will be printed 50 times!")
}

You can access current iteration index as well! It starts at 0 and ends at n-1.

10 times { index ->
  println("This is the $index run.")
}

As usual in case of single-parameter lambdas, current iteration index can be also accessed with it.

10 times {
  println("This is the $it run.")
}

If you prefer even less verbose operators, times happens to be the valid name of the * operator, which - combined with a number - is a pretty readable and obvious way of saying that you want to repeat a loop block for a certain amount of times. Lucky us.

10 * {
  println("Equivalent to '10 times {...}'")
}

Thanks to the fact that these are all inline functions, there is little-to-none runtime overhead for their usage - they compile to pretty much the same byte code as regular Kotlin loops (or Java ones, for that matter). Needless to say, these should be as fast as any other simple loop created with the official API. In fact, methods similar to these obviously should be a part of the official API, available out of the box in the standard library. Duh.

Is it stable?

Definitely. We are proud to announce that all of the extension methods are fully tested on every possible number in each value range. 100% test coverage comes at a price: the full test suite can run for hours due to integers and longs being big their admirable complexity.

Why would you even do that?

Joking aside, I kind of missed the good old classic Java for(int i=0; i loop. Not sure if such syntax is even supported by Kotlin, which I found pretty surprising. (You know, 'var' on loop parameter is not allowed.) Yeah, I'm probably getting old.

Still, I personally don't find the range syntax more readable than times or even *, and ranges actually can be slightly error-prone. For example, the innocent looking for(i in 0..n-1) might loop Int.MAX_VALUE times (instead of being silently ignored) if n happens to be Int.MIN_VALUE. Needless to say, for(i in 1..n) can be less useful in the 0-indexed Java world, as you may have to subtract 1 manually from each value. And using a while loop is usually too verbose if you just want to repeat an action n times.

This "library" might seem like a joke, but - to be honest - I personally find it a decent alternative to numeric ranges, which is both easy to read and pretty useful for all kinds of debugging and testing stuff when all you want is to set up a simple loop as quickly as possible. And I didn't want to ship it with a complete complex utility library. Sue me.

Equivalents

var i = 0
while(i < n) {
  // Do something.
  i++
}

Too verbose. Next.

var i = -1
while(++i < n) {
  // Do something.
}

Not even trying.

for(i in 0..n-1) {
  // Do something.
}

"Crashes" on Int.MIN_VALUE - other than that, this seems to be a sensible way to set it up.

for(i in 1..n) {
  val index = i - 1
  // Do something.
}

Awkward if you need iteration indexes to start with 0.

for(i in 0 until n) {
  // Do something.
}

Verbose. Ish.

(0..n-1).forEach { i ->
  // Do something.
}

(0 until n).forEach { i ->
  // Do something.
}

This might be my personal favorite, but it still seems more verbose than necessary.

inline operator fun IntRange.invoke(action: (Int) -> Unit) {
  for (i in this) action(i)
}

// Given the operator extension, you can do this:
(0..n-1) { i ->
  // Do something. 
}

I pity maintainers of your code if you do this, but I have got to admit it looks unsettlingly tempting.

repeat(n) { i ->
  // Do something.
}

...Um, wait, is this library actually necessary?

How do I include this beauty in my project?

Easily - its already on Maven Central.

Maven

<dependency>
  <groupId>com.github.czyzbygroupId>
  <artifactId>kotlin-timesartifactId>
  <version>1.0version>
dependency>

Gradle

compile 'com.github.czyzby:kotlin-times:1.0'
compile group: 'com.github.czyzby', name: 'kotlin-times', version: '1.0'

Working with the sources

Since this library consists of a single Kotlin file, you can just copy the extension methods to your application and modify them however you like. You can also clone this repository and use Gradle to set up this project, if you really want to.

The code is dedicated to public domain, so feel free to do anything. Just so you know.

Variations

If you're feeling brave, try refactoring times to something like x for this awkwardly short syntax without overloaded operators: 8 x { println("Will work just fine.") }. Life is a sandbox.

The future

Our experts are currently working on extension methods for other numeric types. Hopefully, if the project is not aborted by then, the official 2.0 version will be released in 2042.

Contribution

If you do not think that kotlin-times is perfect in every way for some reason, you can create an issue or open a pull request. Thanks in advance.

You might also like...
SimpleYelp - A basic clone of the restaurant review app, Yelp. This app has just one screen, but the data is fetched from the Yelp API
Alternative to DreamStorageService, but instead of storing files on a database, it is stored on the file system itself.

EtherealGambi Alternative to DreamStorageService, but instead of storing files on a database, it is stored on the file system itself. I made this beca

Candroid Browser is a replacement web browser for Candroid. It is designed to replace the AOSP browser, but not Google Chrome. It will be based on a privacy friendly WebKit engine fork.
Candroid Browser is a replacement web browser for Candroid. It is designed to replace the AOSP browser, but not Google Chrome. It will be based on a privacy friendly WebKit engine fork.

Candroid Browser Candroid Browser is a replacement web browser for Candroid. It is designed to replace the AOSP browser, but not Google Chrome. It wil

An Android Image compress library, reduce's the size of the image by 90% without losing any of its pixels.
An Android Image compress library, reduce's the size of the image by 90% without losing any of its pixels.

Image Compressor An Android image compress library, image compressor, is small and effective. With very little or no image quality degradation, a comp

Desenvolvimento de um CRUD sabendo lidar com requisições GET, POST, PUT e DELETE. E CAMADA DE PERSISTENCIA

API-REST-com-Kotlin-e-Spring-Boot Aprendemos nesse projeto: Parte 1 - DESENVOLVIMENTO WEB 1- Criação de classes de domínio que representam os recursos

Github User App for searching Github Users and get several information from it.
Github User App for searching Github Users and get several information from it.

GithubUserApp Github User App for searching Github Users and get several information from it. This code implement with Coroutines, Retrofit, Architect

This is a skeleton project for Zircon users that can be used to get started with Zircon.
This is a skeleton project for Zircon users that can be used to get started with Zircon.

Zircon Kotlin Skeleton Project This is a skeleton project for Zircon users that can be used to get started with Zircon. Getting started This project w

Therapeutic is a platform to help easily connect patients or generally anyone struggling to get through tough times with motivating content and  professional therapists.
Therapeutic is a platform to help easily connect patients or generally anyone struggling to get through tough times with motivating content and professional therapists.

Therapeutic Apk - https://github.com/develNerd/Therapeutic/blob/main/androidApp/release/androidApp-release6.apk Therapeutic is a Kotlin Mobile Multipl

EduApp is a mini e-learning platform based on udemy's public api. It has 4 main navigation destinations (Home, Search, Wishlist, Cart). Users can search courses from different categories and get real-time results from the api using Chips for a smooth filtering experience. It has different theme for dark mode.
Comments
  • Javadocs and Dokka documentation

    Javadocs and Dokka documentation

    Current Gradle build fails to generate a proper javadoc JAR. However, Dokka can be used instead of the default javadoc Gradle task to generate documentation for the project. (Even though Java-based documentation for Kotlin extension methods is not something you need everyday.)

    enhancement 
    opened by czyzby 0
  • Support unsigned times in Kotlin 1.3

    Support unsigned times in Kotlin 1.3

    Kotlin 1.3 introduced unsigned integer types.

    Unsigned numbers domain is good to represent a non-negative number of repetitions. This library could benefit from them by providing overloads of times extension for unsigned numbers.

    enhancement 
    opened by ilya-g 1
Automatically generates UI demos which allow users to call any function with any parameters

Automatically generates UI demos which allow users to call any function (including composable ones) with any parameters. Useful for building demo screens in playground apps of various design systems.

Anton Popov 3 Jul 28, 2022
🟣 Opinionated Kotlin libs, DSLs and frameworks to build better web apps

Tegral Tegral is an opinionated collection of Kotlin frameworks, libraries, helpers and DSLs that help you make awesome apps, from web back-ends and b

Zoroark 21 Dec 22, 2022
A Simple Android library to get the number of words and give you the time it will take you to finish an article/story.

MinRead A Simple Android library to get the number of words and give you the time it will take you to finish an article/story. Prerequisite Androidx K

Nwokocha wisdom maduabuchi 36 Nov 17, 2021
Kotlin-koans - Kotlin Koans are a series of exercises to get you familiar with the Kotlin Syntax

kotlin-koans-edu Kotlin Koans are a series of exercises to get you familiar with

null 1 Jan 11, 2022
NPS android library to get the feedback you need from users

netpromoterscore NPS android library helps you to get the feedback you need from the users Gradle Dependency: implementation 'com.github.quantumlibs:n

Nithin Naubad 1 May 12, 2022
This is a template to help you get started building amazing Kotlin applications and libraries.

Welcome to the Starter This is a template to help you get started building amazing Kotlin applications and libraries. Over time, examples will be comp

Backbone 8 Nov 4, 2022
This project is basically PowerNukkit but just in Kotlin (check out the original PowerNukkit source here: https://github.com/PowerNukkit/PowerNukkit)

Introduction Nukkit is nuclear-powered server software for Minecraft: Pocket Edition. It has a few key advantages over other server software: Written

Chrones 5 Jul 7, 2021
Repo: Programming problems with solutions in Kotlin to help avid Kotlin learners to get a strong hold on Kotlin programming.

Kotlin_practice_problems Repo: Programming problems with solutions in Kotlin to help avid Kotlin learners to get a strong hold on Kotlin programming.

Aman 0 Oct 14, 2021
This Kotlin Multiplatform library is for accessing the TMDB API to get movie and TV show content. Using for Android, iOS, and JS projects.

Website | Forum | Documentation | TMDb 3 API Get movie and TV show content from TMDb in a fast and simple way. TMDb API This library gives access to T

Moviebase 37 Dec 29, 2022
A custom view for rating which easy to make and use, but function is excellent

QRatingView A custom view for rating which easy to make and use, but function is excellent Effect Picture Properties <declare-styleable name="QRat

QCoder 1 Dec 3, 2021