0

I tried it by the following program but it shows the error that kotlin variable is expected:

[enter image description here

crgarridos
  • 8,758
  • 3
  • 49
  • 61
  • 5
    Hi! try to type the code in your question, instead of taking a screenshot! You'll get better answer. – RLave Jul 19 '18 at 12:27
  • Here is the clear answer -> https://stackoverflow.com/questions/45377802/swap-function-in-kotlin – MrVasilev Jun 17 '19 at 06:29

4 Answers4

4

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")
}
1

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 }
Roland
  • 22,259
  • 4
  • 57
  • 84
0

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
Asim
  • 161
  • 1
  • 12
0

You can use kotlin standarad function named as 'also'.

var a = readLine()!!
var b = readLine()!!
a = b.also { b = a }
Nikunj Joshi
  • 556
  • 5
  • 10