我试图了解函数部分应用程序在 Scala 中的工作原理。
为此,我构建了这个简单的代码:
object Test extends App {
myCustomConcat("General", "Public", "License") foreach print
GeneralPublicLicenceAcronym(myCustomConcat(_)) foreach print
def myCustomConcat(strings: String*): List[Char] = {
val result = for (s <- strings) yield {
s.charAt(0)
}
result.toList
}
def GeneralPublicLicenceAcronym (concatFunction: (String*) => List[Char] ) = {
myCustomConcat("General", "Public", "License")
}
}
myCostumConcat函数输入一个字符串数组,它返回一个包含每个字符串第一个字母的列表。
所以,代码
myCustomConcat("General", "Public", "License") foreach print
将在控制台上打印:GPL
现在假设我想编写一个函数来生成 GPL 首字母缩写词,使用(作为输入参数)我之前的函数提取每个字符串的第一个字母:
def GeneralPublicLicenceAcronym (concatFunction: (String*) => List[Char] ): List[Char] = {
myCustomConcat("General", "Public", "License")
}
使用部分应用程序运行这个新功能:
GeneralPublicLicenceAcronym(myCustomConcat(_)) foreach print
我收到此错误:
错误:(8, 46) 类型不匹配;发现:Seq[String] required: String GeneralPublicLicenceAcronym(myCustomConcat(_)) foreach print
为什么?在这种情况下我可以使用部分应用程序吗?