10

What is the equivalent of Java Scanner in Kotlin?

I have used readLine() but I'd like to know whether it's type safe or not?

UmAnusorn
  • 7,853
  • 8
  • 57
  • 89
esu
  • 1,470
  • 6
  • 16
  • 28
  • What do you mean by 'type safe'? `readLine()` is supposed to return a `String` or `null` if it reached the end of input. I see no possibility to violate type safety since no types other than `String?` are involved. – hotkey Feb 27 '18 at 10:07
  • You can still use `Scanner` in Kotlin if you want to read primitive types directly without handling parsing/casting, since it is fully compatible with Java – user2340612 Feb 27 '18 at 10:11
  • Using Scanner we can read the values as int, String etc. But `readLine()` always return a String. Instead of type cast the value every time, i wish to read the value as nextInt() or nextString(). – esu Feb 27 '18 at 11:05

2 Answers2

10

You can try something like this

val scan = Scanner(System.`in`)

val n = scan.nextLine().trim().toInt()

Since "in" is a Kotlin keyword

UmAnusorn
  • 7,853
  • 8
  • 57
  • 89
5

Kotlin reuses many existing Java libraries and it's perfectly fine to do so with Scanner. Otherwise, readLine simply uses System.in as you can observe here, which might be a simple alternative for you.

s1m0nw1
  • 56,594
  • 11
  • 126
  • 171