繁体   English   中英

Scala链接函数与andThen类型不匹配

[英]Scala chaining functions with andThen type mismatch

我有一堆函数可以清理文本并将它们分成单词。 最小的例子:

val txt = "Mary had a @little \nlamb"
val stopwords = Seq("a")
def clean(text: String): String = text.replaceAll("\n*\r*", "")
def tokenize(text: String): Seq[String] = text.split("\\s")

val cleaned = clean(txt)
val tokens = tokenize(cleaned)

此代码按预期工作。 然而,不是真的惯用。 我原本希望这样做:

clean(txt) andThen tokenize

但编译器抱怨错误type mismatch; required: Char => ? type mismatch; required: Char => ? 在tokenize函数。

我在这里错过了什么?

clean返回一个String 你试图在String实例上使用andThen (因为你用clean(txt)调用方法 )并且编译器将它推断为PartialFunction[Char, ?] (因为WrappedString继承了继承PartialFunction[Char, A] AbstractSeq[Char] PartialFunction[Char, A] )。 这就是你看到类型不匹配的原因。 如果要将两者组合在一起,请使用eta-expansion将它们转换为函数类型:

val res = clean _ andThen tokenize
println(res(txt))

函数组合适用于Scala函数,而不是方法 (有区别),这就是为什么我们必须首先将方法扩展为函数( clean _ ),然后编译器将能够为我们推断tokenize而不需要手动扩展它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM