I tried it by the following program but it shows the error that kotlin variable is expected:
[
I tried it by the following program but it shows the error that kotlin variable is expected:
[
This is not the traditional way, but anyway:
fun main(args: Array <String> ) {
var a = readLine()!!.toInt()
var b = readLine()!!.toInt()
println("a=$a and b=$b")
val c = a + b
a = c - a
b = c - b
println("now a=$a and b=$b")
}
This is the traditional way:
fun main(args: Array <String> ) {
var a = readLine()!!.toInt()
var b = readLine()!!.toInt()
println("a=$a and b=$b")
val c = a
a = b
b = c
println("now a=$a and b=$b")
}
and this is the Kotlin way with only 2 variables:
fun main(args: Array <String> ) {
var a = readLine()!!.toInt()
var b = readLine()!!.toInt()
println("a=$a and b=$b")
a = b.also { b = a }
println("now a=$a and b=$b")
}
I do not know, why you want to swap the values, but depending on what you want to do exactly and if you do not require the variables, here is another approach using a Pair
:
(readLine()!! to readLine()!!)
.also(::println) // optional
.map { a, b -> b to a }
.also(::println) // optional
which for the input 1
and 2
prints:
(1, 2)
(2, 1)
For further swapping possibilities you may also want to look at: Swap Function in Kotlin
Example with Enter a
, etc.:
val ask : (String) -> String = {
print(it)
readLine()!!
}
(ask("Enter a: ") to ask("Enter b: "))
.map { a, b -> b to a }
Use the power of Kotlin type casting and it's done!!
var a = readLine()!!
var b = readLine()!!
//print
val c = a.toInt() + b.toInt()
b = (c-b.toInt()) as String
a = (c-a.toInt()) as String
//print
You can use kotlin standarad function named as 'also'.
var a = readLine()!!
var b = readLine()!!
a = b.also { b = a }