0

I'm new to Kotlin and I'm playing with the for loop, in Kotlin Script (*.kts file) I have this in the file:

for (i in 1..5) print("$i, ")

I did think it would print the number 1 through 5 separated by commas in one line like this:

1, 2, 3, 4, 5, 

But instead I don't get any output on the command line. I'm running this on a Mac via

kotlin ranges.kts

If I put anything behind this single for loop, like a seperate println() or if I replace the print in the loop with println, it works and gives me output.

I don't get this behaviour. Can anyone explain this to me?

Edit1: Versions: kotlin: 1.3.71 MacOS 10.15.4 (Catalina)

3
  • Well for me it does prints: 1, 2, 3, 4, 5, ##scratch##generated##kotlin.Unit Commented Apr 15, 2020 at 8:31
  • @AnimeshSahu on which platform and version of os & kotlin? Commented Apr 24, 2020 at 7:24
  • Kotlin 1.3.72 @ Windows 10 1909. Maybe it happened because i was using REPL in running the script. Commented Apr 24, 2020 at 7:46

1 Answer 1

3

This has nothing to do with the for loop and everything to do with print. It works if you add System.out.flush() at the end of the script. By default, writes to System.out (which print uses under the hood) don't always flush, and its likely that the Kotlin script runner isn't flushing the standard output stream before exiting.

This is also why using println works, as you noted -- if you look at the implementation of println in PrintStream, you'll see that it does flush its internal text and character output streams.

I created issue https://youtrack.jetbrains.com/issue/KT-38263.

Sign up to request clarification or add additional context in comments.

1 Comment

In addition: prinln() calls are far more common than print(), for this reason and others. If you want to print several things you can format them first — e.g. println((1..5).joinToString()).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.