在阅读教程时,我看到了一段代码,为了理解这一点,请尝试编写一个示例函数并对其进行调用。
由于我是scala的新手,所以找不到从哪里开始。
val flow3: Flow[Int, Int, NotUsed] = Flow[Int].statefulMapConcat {
() =>
var sequence = 0
println("statefulMapConcat func call")
i =>
sequence = sequence + i
List(sequence)
}
以上两件事对我来说很奇怪
定义是:
def statefulMapConcat[T](f: () ⇒ Out ⇒ immutable.Iterable[T]): Repr[T] =
via(new StatefulMapConcat(f))
我的尝试!
def suffix(x: String): String = x + ".zip"
// not sure this is true
def test1(f: String ⇒ String ⇒ String): String = f("a1")("a2") + "a3"
// not sure this is also a true definition
def test2(f: String ⇒ String ⇒ String): String = f + "a4"
// compile is okay but can not call this
var mytest= test1{
a => a + "a5"
b => b + "a6"
}
// giving even compile time error
test(suffix(suffix("")))
答案 0 :(得分:0)
var mytest= test1{
a => a + "a5"
b => b + "a6"
}
在此序言中,您无法调用mytest,因为“ mytest”不是函数,而是“ test1”函数求值的结果。 “ mytest”是一个字符串值。因此,您可以将代码替换为以下代码,并且仍然可以编译:
var mytest: String= test1{
a => a + "a5"
b => b + "a6"
}
您的第二个示例还有另一个问题。您正试图调用“测试”函数,该函数传递已评估的字符串“ suffix(suffix(“”)))“的结果。
要使其编译,您需要创建返回函数的函数,然后将其传递给“测试”(1或2)
def functionReturiningFunciton(s:String):String=>String = (k) => suffix(suffix(""))
val f: String => String => String = functionReturiningFunciton // convert to value
test1(f)
test2(f)
或者您甚至可以直接传递“ functionReturiningFunciton”,因为它将自动转换为val
def functionReturiningFunciton(s:String):String=>String = (k) => suffix(suffix(""))
test1(functionReturiningFunciton)
test2(functionReturiningFunciton)
甚至是这样
test1(s => k => suffix(suffix("")))
注意。当您这样做时:
var mytest= test1{
a => a + "a5"
b => b + "a6"
}
如果您取消对代码的加糖。您实际上是在这样做:
def someFunction(a:String):String=>String = {
a + "a5" // this is evaluated but ignored
b => b + "a6" //this is what returned by someFunction
}
var mytest:String= test1{someFunction}
定义是:
def statefulMapConcat[T](f: () ⇒ Out ⇒ immutable.Iterable[T]): Repr[T] = via(new StatefulMapConcat(f))
statefulMapConcat函数将参数为零的另一个函数作为参数,并返回另一个参数为“ Out”并返回Iterable [T]的函数