0

Now i understand understand this code output

I was reading Atomic Kotlin and stumbled upon this piece of code that just doesn't make sense to me. Can someone explain why it outputs "Kotlin!"? fun main() { for (ch in "Jnskhm ") { print(ch + 1) } }

23rd Feb 2022, 3:54 PM
Flora Maxine
Flora Maxine - avatar
4 Réponses
+ 5
Yeah Kotlin does magic! Look closely at each letters in the string "Jnskhm ", and then, think of the one next letter after that. J -> K n -> o s -> t k -> l h -> i m -> n " " -> ! (space becomes exclamation mark) To understand this, play around with value used to increment variable <ch> inside the for...loop. So you understand what the incremental value does.
23rd Feb 2022, 4:07 PM
Ipang
+ 4
Flora Maxine When you add a number in a character then it add ASCII value so if ASCII value of J is 10 then 10 + 1 = 11 which would be K. So in this example: J + 1 = K n + 1 = o m + 1 = n
23rd Feb 2022, 4:09 PM
A͢J
A͢J - avatar
+ 3
Flora Maxine Try this example in Code Playground, you will understand better: fun main(args: Array<String>) { val c = 'a'; val num = c.toInt() println (num) println (c + 1); val num1 = num + 1 println (num1) println (num1.toChar()) }
23rd Feb 2022, 4:18 PM
A͢J
A͢J - avatar
+ 1
WOW! IT JUST BLEW MY MIND! Thank you!
23rd Feb 2022, 4:09 PM
Flora Maxine
Flora Maxine - avatar