I am trying to understand how andThen works in Scala.
我试图了解如何和然后在Scala中工作。
Here's the code:
这是代码:
def collectNames(fromList: List[Map[String,String]]) = {
fromList.foldLeft(new StringBuffer)((x,y) => {
x.append(y("Name")).append(",")
}).toString
}
def getOriginalList = List(Map("Name" -> "NS","Age" -> "50"),Map ("Name" -> "SS", "Age" -> "45"))
getOriginalList andThen collectNames
The compiler finds this disagreeable. It seems that collectNames is being given a Map[String,String]
rather than a List[Map[String,String]]
.
编译器发现这令人不愉快。似乎collectNames被赋予Map [String,String]而不是List [Map [String,String]]。
What does it take me to be able to write that little snippet of 'flowing' code correctly?
能够正确编写那些“流动”代码的小片段我需要什么?
1 个解决方案
#1
The problem is that getOriginalList _
is a Function0
(i.e () => R
) and has no compose
or andThen
.
问题是getOriginalList _是一个Function0(即()=> R)并且没有compose或andThen。
Therefore, you this won't compile: getOriginalList _ andThen collectNames _
因此,你不会编译:getOriginalList _然后collectNames _
Now if getOriginalList
can be treated as a partially applied function1, it will work:
现在,如果可以将getOriginalList视为部分应用的function1,它将起作用:
def getOriginalList(a: Any) = List(Map("Name" -> "NS","Age" -> "50"))
val composed = getOriginalList _ andThen collectNames _
But in your case, composition-wise, you should probably consider getOriginalList
as a val
and use it as a function argument:
但在你的情况下,在组合方面,你应该将getOriginalList视为val并将其用作函数参数:
def collectNames(fromList: List[Map[String,String]]) = {
fromList.foldLeft(new StringBuffer)((x,y) => {
x.append(y("Name")).append(",")
}).toString
}
def getOriginalList = List(Map("Name" -> "NS","Age" -> "50"),Map ("Name" -> "SS", "Age" -> "45"))
val comp = collectNames _ andThen ((s: String) => s.length())
val n = comp(getOriginalList) // 6 = ("NS,SS,".length())
#1
The problem is that getOriginalList _
is a Function0
(i.e () => R
) and has no compose
or andThen
.
问题是getOriginalList _是一个Function0(即()=> R)并且没有compose或andThen。
Therefore, you this won't compile: getOriginalList _ andThen collectNames _
因此,你不会编译:getOriginalList _然后collectNames _
Now if getOriginalList
can be treated as a partially applied function1, it will work:
现在,如果可以将getOriginalList视为部分应用的function1,它将起作用:
def getOriginalList(a: Any) = List(Map("Name" -> "NS","Age" -> "50"))
val composed = getOriginalList _ andThen collectNames _
But in your case, composition-wise, you should probably consider getOriginalList
as a val
and use it as a function argument:
但在你的情况下,在组合方面,你应该将getOriginalList视为val并将其用作函数参数:
def collectNames(fromList: List[Map[String,String]]) = {
fromList.foldLeft(new StringBuffer)((x,y) => {
x.append(y("Name")).append(",")
}).toString
}
def getOriginalList = List(Map("Name" -> "NS","Age" -> "50"),Map ("Name" -> "SS", "Age" -> "45"))
val comp = collectNames _ andThen ((s: String) => s.length())
val n = comp(getOriginalList) // 6 = ("NS,SS,".length())