带有 andThen 类型不匹配的 Scala 链接函数 [英] Scala chaining functions with andThen type mismatch
问题描述
我有很多功能可以清理文本并将它们拆分为单词.最小示例:
I have a bunch of functions that clean text and splits them into words. Minimal example:
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)
此代码按预期工作.然而并不是很地道.我曾希望这样做:
This code works as expected. However not really idiomatic. I had hoped to do this:
clean(txt) andThen tokenize
但是编译器抱怨这个错误 type mismatch;要求:字符 =>?
在 tokenize 函数中.
But the compiler complains about this with the error type mismatch; required: Char => ?
at the tokenize function.
我在这里遗漏了什么?
推荐答案
clean
返回一个 String
.您正在尝试在 String
实例上使用 andThen
(因为您正在使用 clean(txt)调用 methodcode>) 并且编译器将其推断为
PartialFunction[Char, ?]
(因为 WrappedString
继承了 AbstractSeq[Char]
,它继承了 PartialFunction[Char, A]
).这就是您看到类型不匹配的原因.如果要将两者组合在一起,请使用 eta-expansion 将它们转换为函数类型:
clean
returns a String
. You're trying to use andThen
on a String
instance (since you're invoking the method with clean(txt)
) and the compiler infers it as a PartialFunction[Char, ?]
(because WrappedString
inherits AbstractSeq[Char]
which inherits PartialFunction[Char, A]
). That is why you're seeing the type mismatch. If you want to compose the two together, turn them into function types using eta-expansion:
val res = clean _ andThen tokenize
println(res(txt))
函数组合适用于 Scala 函数,而不是 方法(有区别),这就是为什么我们必须首先将方法扩展为函数(clean _
),然后编译器就可以为我们推断出tokenize
,而无需手动扩展它.
Function composition works on Scala functions, not methods (there is a distinction), and that is why we have to first expand the method to a function (clean _
), and then the compiler will be able to infer tokenize
for us without the need to manually expand it.
这篇关于带有 andThen 类型不匹配的 Scala 链接函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!