2016-09-25 7 views
1

ファイル処理のためのScala cook bookを使い、コードの下に来ました。 IDEで実行しようとしましたが、エラーが発生しました。私は何かが欠けている、私はアレイの前にそのような構文に遭遇したことはありません。一般に配列解体構文

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()} 
    } 
+0

この構文は、基本的に等号の左側に適用されるパターンマッチングです。配列は、左側の名前付きの値に分解されています。 – Samar

答えて

4

、この機能はExtractor Patternsと呼ばれ、unapply/unapplySeqインスタンスメソッドを持つ任意のオブジェクトに対して有効になっています。それは、特定のインデックス(0から始まる)で与えられた値を変数に直接抽出することを可能にします。

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

@ユヴァイありがとう! –

+0

@PriyaranjanSwainあなたはようこそ –

0

収益、費用は、利益が小文字の単語で始める必要があります。

は具体的には、あなたの問題は、変数名を小文字する必要がある抽出パターンに大文字の変数名を使用していることです。次のコード

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

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

パターン上で動作しますがextractor patternと呼ばれています。

0

他の人が触れたように、それはextractor patternsと呼ばれています。コードを次のように書き換えることができます

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