Scala Convert String to Long

1. Introduction

Converting a string to a long integer is a common requirement in Scala, especially when dealing with numerical data that comes in text format. Scala provides straightforward ways to perform this conversion, which are essential for data manipulation and processing. This blog post will explore methods to convert a string to a long in Scala.

2. Program Steps

1. Define strings that represent long integer values.

2. Demonstrate how to convert these strings to longs using Scala's built-in methods and handling potential exceptions.

3. Print the results to verify the conversion.

4. Execute the code to observe the behavior of each conversion method.

3. Code Program

object StringToLongDemo extends App {
  val numberString = "1234567890"
  val invalidNumberString = "123abc"

  // Using toLong
  val longNumber = numberString.toLong
  println(s"Using toLong: $longNumber")

  // Using toLong with exception handling
  try {
    val invalidLongNumber = invalidNumberString.toLong
    println(s"Using toLong with exception handling: $invalidLongNumber")
  } catch {
    case e: NumberFormatException => println("Exception caught: Not a valid long integer")

  // Using Option with toLong
  val result = toLong(numberString)
  println(s"Using Option with toLong: $result")

  // Helper method to convert string to Option[Long]
  def toLong(s: String): Option[Long] = {
    try {
    } catch {
      case _: NumberFormatException => None


Using toLong: 1234567890
Exception caught: Not a valid long integer
Using Option with toLong: Some(1234567890)


1. The toLong method directly converts the string numberString to a long. This method throws a NumberFormatException if the string is not a valid long integer.

2. Exception handling is demonstrated with invalidNumberString.toLong. Attempting to convert "123abc" to a long results in a NumberFormatException, which is caught and handled.

3. The toLong method with Option is a safer way to attempt conversion. It returns Some(long) if successful or None if the conversion fails, helping to avoid exceptions and handle invalid inputs gracefully.