Scala语言中函数返回值标注"String => String"的含义是什么?
String => String as a Return Type in Scala Hey there! Let's break down exactly what that String => String notation means in your Scala function definition—it's one of those functional programming concepts that clicks once you see it in action.
First off, String => String is a function type in Scala. Think of it as a blueprint for a function that takes a single String as input and spits out another String as output.
Let's walk through your example line by line:
def myFunction(line: String): String => String = { _.toLowerCase() }
myFunctiontakes aStringparameter calledline(fun fact: in this specific case,lineisn't even used—right now the function just returns a fixed string-transforming function no matter what input you pass it).- The
: String => Stringpart tells us that instead of returning a plainString,myFunctionreturns an entire function. That returned function is the_.toLowerCase()part—a shorthand for the anonymous function(s: String) => s.toLowerCase().
To make this concrete, here's how you'd use this in practice (like you probably did in the REPL):
// Grab the returned function from myFunction val transformToLower = myFunction("doesn't matter what I put here") // Now transformToLower is a function that takes a String and returns its lowercase version transformToLower("HELLO SCALA!") // returns "hello scala!"
As a side note, String => String is just syntactic sugar for Function1[String, String]—the standard library trait that defines single-argument functions in Scala. The => syntax is just a cleaner way to write it.
内容的提问来源于stack exchange,提问作者Isaac Amezcua

