2015-10-13 60 views
1

我是Scala的新手,但對Haskell有一些經驗。我做了以下操作:如何從Scala返回一個值def

import scala.io.Source 

val fileContent = Source.fromFile(filename).getLines.toList 
val content = fileContent.map(processLine) 

def processLine(line: String){ 
    val words = line.split("\\s+") 
    println((words(0), words(1))) 
} 

此處processLine不返回任何內容,因此內容現在是所有項目的空返回值列表。我認爲解決辦法是包括ProcessLine從一個返回值,但斯卡拉不喜歡:

warning: enclosing method processLine has result type Unit: return value discarded 

所以,我怎麼能修改ProcessLine從以便它可以被用來創建非空的元組的列表內容中的價值?如何用多行聲明一個lambda函數?

var nonLinearTrainingContent = fileContent.map(x=> { 
     val words = x.split("\\s+") 
     (words(0), words(2)) 
     }) 

回答

2

有兩件事情,防止結果返回:

  1. println回報Unit
  2. 你的函數確定指標是一個方法的速記返回Unit

這會給你你想要的結果:

def processLine(line: String) : (String,String) = { 
    val words = line.split("\\s+") 
    val result = (words(0), words(1)) 
    println(result) 
    result 
} 

至於問表示爲函數相同:

val processLineFun : String => (String, String) = line => { 
    val words = line.split("\\s+") 
    val result = (words(0), words(1)) 
    println(result) 
    result 
} 
+0

andreas。你也可以用lambda函數替換processLine嗎?我認爲這將完成/補充主題答案。 – stian

1

製作的元組(字(0),字(1))最後ProcessLine從功能的線路:

由於在這個線程有用的信息,我也有一個lambda表達式寫它:

def processLine(line: String) = { 
    val words = line.split("\\s+") 
    println((words(0), words(1))) 
    (words(0), words(1)) 
} 

編輯:對多行lambda函數使用大括號或單獨的運算符與';'對於一個行拉姆達

EDIT2:固定收益型

+0

這仍然會返回'Unit' –

+0

@nyavro。我試過了,這並不像Peter提到的那樣工作。 – stian

+0

應該在方括號前面加上'=',在大括號中,請參閱我的編輯 – Nyavro

相關問題