Kotlin readLine gives error in a basic program where input is taken from user and the same is shown as output - kotlin

The following code :
fun main(args: Array<String>) {
print("Write anything here: ")
val enteredString = readLine()
println("You have entered this: $enteredString")
}
gives the following error in KotlinPlayground :
Write anything here: You have entered this: null
Here, the user doesn't get an opportunity to enter input. After the initial print statement gets executed, the compiler is not waiting for the user to give input and skips to the next print statement. Why is it happening? I have tried the same in several other online Kotlin compilers but I am getting the same error.

There's no error. readLine just returns null (because Kotlin Playground doesn't have a console to read from), and it's printed as expected.
E.g. on https://ideone.com/ you can say what to use for input and it'll print that line (though its Kotlin version is pretty old).

Because Kotlin playground have no user input console and this is not an error. For user input you can either use https://ideone.com/ or
https://www.jdoodle.com/compile-kotlin-online/
I will recommend you to use the second on which is jdoodle. It is pretty much faster to run and read user input and almost use the latest version of Kotlin and JRE.
And if you like to play (run) with command line argument then it will good for you with jdoodle.

This can be done in Kotlin Playground by using JS as the destination platform - click on the JVM dropdown (top left, to the right of the kotlin version) and change to JS.
Now you can call JavaScript - only using constant strings, e.g.
fun main() {
val name = js("prompt('Please enter your name', 'Bob')")
println("Hello $name")
}
For another example, using a common function, see https://pl.kotl.in/MkhfYNS47
Note: if you try this:
fun promptName(default: String = "") {
return js("prompt('Please enter your name', '$default')")
}
You will get a compilation error - Argument must be string constant.
Note that JS IR as an option ran much slower and had an issue with default type needing to be stated for the linked code

Related

What is the difference between readLine() and readlnOrNull() in Kotlin?

As mentioned in Kotlin API document, readLine() returns the line read or null if end of file has already been reached but it is the same functionality as readlnOrNull(). So what is the difference here?
I know that readlnOrNull() and readln() have been introduced in Kotlin 1.6 for the purpose of null safety but I can't understand why readlnOrNull() introduced when readLine() exist before.
They added readlnOrNull as an alias of readLine for the sake of preserving the convention that each standard library function that throws a RuntimeException has an “orNull” version that returns null instead of throwing. It was added when readlnwas added. It’s so the matching function with this behavior can be easily found. If readLn had existed from the earliest version of Kotlin, then they might never have created a redundant readLine function that matches the behavior of readlnOrNull. They have not deprecated readLine because there’s nothing wrong with its behavior and it’s concise.
readLine() and readlnOrNull() are both methods used in Kotlin for reading input from the user.
readLine() is used to read a line of text from the standard input and returns a string. If the user does not provide any input or an error occurs, this method throws an IOException.
scss
val input = readLine()
readlnOrNull() is similar to readLine(), but instead of throwing an exception, it returns null if the user does not provide any input or an error occurs.
scss
val input = readLine() ?: "No input provided"
In general, it is recommended to use readlnOrNull() as it provides a more flexible and safer way to handle input reading in Kotlin.

Kotlin script: main function does not get called locally, unlike in online judge

I am trying to participate in online Codeforces contests using Kotlin.
My understanding is I should use Kotlin script if my code is contained within a single file.
If I run the following file locally (version 1.6.10):
kotlin just_main.main.kts
// just_main.main.kts
fun main() {
println("Hello World")
}
Nothing happens. I need to add an explicit call for it to actually execute main:
// top_level_call.main.kts
fun main() {
println("Hello World")
}
main()
So far, so normal. The problem occurs when I try to submit my solution to the Codeforces online judge. The judge expects no top-level code and runs the main function instead. So just_main runs fine, but top_level_call produces a compilation error:
Can't compile file:
program.kt:43:1: error: expecting a top level declaration
main()
^
This leads to the awkward situation of me having to add the main() call when I want to try my solution locally, but having to remove it every time I upload an attempt.
Is there a way to have my local Kotlin behave the same as the online judge, meaning implicitly running any main functions (meaning just_main would produce output)?
I haven't found a way to do this with Kotlin script files, but you can also use normal .kt files without having any classes in the file (my understanding is that Kotlin magically turns them into Java class bytecode/files):
kotlinc a.kt && kotlin AKt < a.in
This "runs" a.kt with standard input from a.in.
(And yes I only found this after I already wrote the question)

Kotlin flow execution issue

I'm studying Kotlin and I have a question about the flow execution of the language. I wrote this code into the Kotlin playground:
fun main() {
println("Hello,")
Thread.sleep(5000L)
print("World!")
}
I expected that the program prints "Hello,", then "World!" after 5 seconds (e.g. how it works in Java). However, it prints "Hello, World!" after 5 seconds and nothing before. Am I missing something? I've also tried to insert System.out.flush() after the first print but it didn't work.
Thanks
https://try.kotlinlang.org and https://play.kotlinlang.org only display output after the whole program is done. This shouldn't happen with an "actual" Kotlin compiler / JVM runtime (e.g. in IntelliJ).

Unexpected tokens I'm following a tutorial and we do really the same code but the video was published on 2018

Log.d(tag:"MainActivity", msg:"Email is: " + email)
Log.d(tag:"MainActivity", msg:"Password: $password")
Log.d("MainActivity", "Email is: $email");
Log.d("MainActivity", "Password: $password")
The problem is, that you copied the so-called "Parameter Hints" by IntelliJ.
The parts of your code that end with a double-colon (tag: and msg:) aren't really part of the Kotlin code. Instead, the IDE that the creator of the tutorial was using showed hints for the names of the parameters.
Example
The function
fun add(a: Int, b: Int): Int {
return a + b
}
has two parameters, the first called a and the second called b.
This means when calling this code from IntelliJ, the IDE will show the following hints to the user so that he knows what parameters he is entering:
You can identify these hints by looking at them accurately. They have a different font, are boxed, and have a different background-color. Please note that these hints are not part of the Kotlin code and cannot be written in Kotlin, that's where your Syntax Error comes from.
Have fun learning Kotlin! 👍

Kotlin script (.kts) file -- no println?

I am experimenting with the use of Kotlin as a scripting language. According to their docs, you should be able to run top-level code in a Kotlin script.
A simple "Hello, World" program I wrote using their official example is not outputting any text. It compiles/interprets, terminates successfully, but it appears that the println() statement does nothing
fun main(args: Array<String>) {
println("Hello, World!")
}
Does anyone know where I can find a table / summary of what is actually supported when using Kotlin as a scripting language? What am I missing in making it do a simple print statement.
I am running using a Kotlin SDK installed via sdkman on Ubuntu. Running from the vanilla terminal provided with Ubuntu. The expected output would be a line where "Hello, World!" is shown, but there is no output at all.
A function in it self does not get executed. Its a declaration like a variable. In a script it must be invoked.
fun main() { // removed unused args
println("Hello, World!")
}
// Add this
main()