Reputation: 2050
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
But the compiler complains about this with the error type mismatch; required: Char => ?
at the tokenize function.
What am I missing here?
Upvotes: 4
Views: 835
Reputation: 149538
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))
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.
Upvotes: 4