2015-10-13 62 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

相关问题