Krishna Kalyan Krishna Kalyan - 2 months ago 31
Scala Question

Console input from user in scala leads to deprecation warning

I have written a simple program in

scala
to addd numbers.

object AplusB {
def main(args: Array[String]): Unit = {
val rawInput = Console.readLine()
val nums = rawInput.split(" ")
println(args(0).toInt + args(1).toInt)
}

}


while trying to compile above I get a warning

scalac AplusB.scala -deprecation
AplusB.scala:5: warning: method readLine in class DeprecatedConsole is deprecated: Use the method in scala.io.StdIn
val rawInput = Console.readLine()


What can I do to fix this?. What are the best practices while trying to read data from console?.

Answer

First, allow me to suggest an alternative solution that is not deprecated.

import scala.io.StdIn

object AplusB {

  def main(args: Array[String]): Unit = {
    val rawInput = StdIn.readLine()
    val nums = rawInput.split(" ")
    println(args(0).toInt + args(1).toInt)
  }

}

The Console.readLine() method is deprecated and I believe StdIn.readLine(), was introduced to replaced it.

When a method is deprecated, that means this method may be removed in some future release. This future release could be next release or even few releases ahead. I think a deprecated method might not be removed for few releases not to break old code that depends on this method.

A method could be deprecated because it was inefficient for an example, or the language or framework developer realised that it just doesn't make sense to be in this particular class or package and needs to move it, etc.

Comments