You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Scala语言中函数返回值标注"String => String"的含义是什么?

Understanding 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() }
  • myFunction takes a String parameter called line (fun fact: in this specific case, line isn't even used—right now the function just returns a fixed string-transforming function no matter what input you pass it).
  • The : String => String part tells us that instead of returning a plain String, myFunction returns 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 08:52:19