我正在寫一個函數,用於根據數據確定出生在birthYear
中的具有指定gender
(「M」或「F」)的人是否有生命文件(csvData),看起來像這樣:使用scala的工具編寫更好的代碼
( 「1930年, 」67「, 」76「)
(」 1950年, 「65」, 「77」)
( 「1970年,」 64「,」76「)
其中:
第一個數字表示年份
第二個代表一個人
第三的預期壽命代表着女人
例子的壽命:
「一個1930年出生的人的預期壽命爲67歲。」
def expectedAlive(gender: String, birthYear: Int, currentYear: Int): Boolean = {
val age = currentYear-birthYear //gets the person's age
if(gender == "F")//checks for male of female in order to acces the right element
if(csvData.contains(birthYear.toString)//checks if year exists in the database
if(age < csvData.filter(x => x(2).toInt)) //attempts to compare the 3 element in list with age.
else...
else ...
else ...
這裏是我的問題:
我期待在這裏問一個比較字符串一個int。雖然我明白爲什麼它給了我一個錯誤,但我不知道如何解決它。 我看到這樣做的方式是通過編寫if/else語句。但是,據我瞭解,Scala具有強大的語法和功能。
有沒有更好的方法來處理這個使用它們?
請問你能分享一下你的csvData obj ect看起來像? – rancidfishbreath
這是一個列表,就像一個頂部 –
對不起,你要求的對象。這是一個變量:val csvData = fromFile(「file-name.csv」)。它直接從文件讀取並將其放入列表中。 –