Priyaranjan Swain
Priyaranjan Swain

Reputation: 361

Array deconstruction syntax

I was going through Scala cook book for file handling and came across below code. Tried to run it in my IDE, but getting an error. Am I missing anything, I have never come across such syntax before for array.

import java.io.IOException
import scala.io.{BufferedSource, Source}

object ReadingCSVfile extends App {
  var bufferedSource = None: Option[BufferedSource]
  try {
    bufferedSource =
       Some(
         Source.fromFile(
           "C:\\Users\\pswain\\IdeaProjects\\test1\\src\\main\\resources\\finance.csv")
       )

    for(i <- bufferedSource.get.getLines()) {
      val Array(month, Income, Expenses, Profit) = i.split(",").map(x => x.trim)
      println(s"$month $revenue $expenses $profit")
    }
  } catch {
      case e : IOException => print(e.printStackTrace())
    } finally {bufferedSource.get.close()}
  }

Upvotes: 1

Views: 1794

Answers (3)

Hongxu Chen
Hongxu Chen

Reputation: 5350

Like what others have mentioned, it's called extractor patterns. You can rewrite the code as

for(i <- bufferedSource.get.getLines()) {
  i.split(",").map(x => x.trim) match {
  case Array(month, income, expenses, profit) =>
     println(s"$month $revenue $expenses $profit")
  }
}

Upvotes: 0

Yuval Itzchakov
Yuval Itzchakov

Reputation: 149558

In general, this feature is called Extractor Patterns and is enabled for any object that has an unapply/unapplySeq instance method. What it does is allow you to extract the given value at the particular index (start at 0) directly into a variable.

Specifically, your problem is that you're using capitalized variable names in the extractor pattern, where the variable names should be lowercase:

val Array(month, income, expenses, profit) = i.split(",").map(x => x.trim)

Upvotes: 6

Nagarjuna Pamu
Nagarjuna Pamu

Reputation: 14825

Income, Expenses, Profit should start with lower case word.

Following code works

 val Array(month,income,expenses,profit) = i.split(",").map(x => x.trim)

 println(s"$month $income $expenses $profit")

above pattern is called extractor pattern.

Upvotes: 0

Related Questions