2017-09-03 50 views
1

我有以下代码Scala的功能:呼叫内的可变

def func1 : Mylass = ... 
def func2 : Mylass = ... 
def func3 : Mylass = ... 

def function : List[MyClass] = { 
    val funcs = List(func1, func2, func3) 
    for { 
     f <- funcs 
     result = [??? What I shall put here ???] 
    } yield result 
} 

for循环的目的是调用通过一个存储的内部f一个的功能。但我不知道我要放什么来“调用存储在变量f内部的函数”。

我试图把:

result = f() 

但我的IDE提供了编译错误。

非常感谢。

回答

0

您的funcs变量实际上是调用func1,func2func3的结果列表。这些是函数定义。你需要告诉编译器把它们作为函数值,像这样:

def func1 : String = ??? 
    def func2 : String = ??? 
    def func3 : String = ??? 

    def function : List[String] = { 
    val funcs = List(func1 _, func2 _, func3 _) 
    for { 
     f <- funcs 
     result = f() 
    } yield result 
    } 

你可以只yield f()

或者改变你的函数定义以函数值:

val func1 :() => String = ??? 
    val func2 :() => String = ??? 
    val func3 :() => String = ??? 

    def function : List[String] = { 
    List(func1, func2, func3).map(_.apply()) 
    } 
0

你写什么都要工作。 不确定你的问题到底是什么,因为你既没有显示完整的代码示例,也没有显示你得到的实际错误信息。

这编译:

def foo: String = ??? 
def bar: List[String] = for { 
    f <- List(foo _) 
    result = f() 
} yield result 

UPDATE啊,我意识到什么是你的代码错误,阅读对方的回答后:List(foo)创建在这种情况下String(援引foo的结果)的列表(因为foo被声明为没有括号),List(foo _)是一个函数列表,返回String。 所以,你写它的方式,fString,所以f()没有意义。 另一方面,在我的代码片段中,f是一个函数,f()会调用它。

+0

如果for理解是在一个函数内部,并且签名像他提供的那样,那么它就不会编译。 – pedromss

+0

当然,它确实...我会更新答案 – Dima

+0

请注意'='而不是'< - '它很微妙,他可能看不到它。同样,如果在'yield'子句中使用'='可能也是 – pedromss