Home > Software engineering >  Read a tuple from a file in Scala
Read a tuple from a file in Scala

Time:06-05

my Task is to read registrations from a file given like:

Keri,345246,2
Ingar,488058,2
Almeta,422016,1

and insert them into a list(Tuple of (String, Int, Int).

So far I wrote this: enter image description here

The problem is that I don‘t understand why I can't try to cast value2 and value3 to Int even tho they should be Strings because they come from an Array of Strings. Could someone tell me, what my mistake is, I am relatively new to Scala

CodePudding user response:

In Scala, in order to convert a String to an Int you need explicit casting.

This can be achieved like this if you are sure the string can be parsed into a integer:

val values = values(1).toInt

If you cannot trust the input (and you probably should not), you can use .toIntOption which will give you a Option[Int] defined if the value was converted successfully or undefined if the string did not represent an integer.

CodePudding user response:

What is the point of using Scala if you are going to write Java code?

This is how you would properly read a file as a List of case classes.

import scala.io.Source
import scala.util.Using

// Use proper names for the fields.
final case class Registration(field1: String, field2: Int, field3: Int)

// You may change the error handling logic.
def readRegistrationsFromFile(fileName: String): List[Registration] =
  Using(Source.fromFile(fileName)) { source =>
    source.getLines().map(line => line.split(',').toList).flatMap {
      case field1Raw :: field2Raw :: field3Raw :: Nil =>
        for {
          field2 <- field2Raw.toIntOption
          field3 <- field3Raw.toIntOption
        } yield Registration(field1 = field1Raw.trim, field2, field3)

      case _ =>
        None
    }.toList
  }.getOrElse(default = List.empty)

(feel free to ask any question you may have about this code)

  • Related