Can functions use by-name arguments?

def f(x: => Int): String = x.toString
val g = f(_)

What’s the type of g? Scastie displays it as Function1[=> Int, String], but that’s not Scala syntax, is it? What I need to do is pass f as an argument to another function. Can it be done?

defs can be passed as args, as the compiler will implicitly convert them to function literals

1 Like

The REPL seems to be happy with val g:(=> Int) => String = f(_). That is the type that is inferred in the REPL.

2 Likes

By-name is actually a type, but a tricky one.
See this: Make by-name parameters just sugar syntax rather than actual types - Language Design - Scala Contributors

2 Likes

the following (from https://www.slideshare.net/pjschwarz/lambda-expressions-and-java-8-lambda-calculus-lambda-expressions-syntactic-sugar-first-class-functions-second-expedia-tech-know-how-talk-nov-2015) may be useful





1 Like

ahh I didnt even notice the : => in there

may or may not be useful to someone:

1 Like

Since Function[=> Int, String] didn’t work, I didn’t even try (=> Int) => String, but it does work. Doesn’t seem very consistent…