Skip to content

Commit 082e718

Browse files
committed
lambda param inference for overloaded methods
1 parent cde70b7 commit 082e718

File tree

1 file changed

+21
-3
lines changed

1 file changed

+21
-3
lines changed

hand-written.md

Lines changed: 21 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,7 @@ Note that the compiler still has quite a bit of magic to perform behind the scen
8080

8181
#### Lambda syntax for SAM types
8282

83-
The Scala 2.12 type checker accepts a function literal as a valid expression any Single Abstract Method (SAM) type, in addition to the `FunctionN` types from standard library. This improves the experience of using libraries written for Java 8 in Scala. For example, in the REPL:
83+
The Scala 2.12 type checker accepts a function literal as a valid expression for any Single Abstract Method (SAM) type, in addition to the `FunctionN` types from standard library. This improves the experience of using libraries written for Java 8 in Scala. For example, in the REPL:
8484

8585
scala> val runRunnable: Runnable = () => println("Run!")
8686
runRunnable: Runnable = $$Lambda$1073/754978432@7cf283e1
@@ -99,9 +99,27 @@ Note that only lambda expressions are converted to SAM type instances, not arbit
9999

100100
The language specification has the [full list of requirements for SAM conversion](http://www.scala-lang.org/files/archive/spec/2.12/06-expressions.html#sam-conversion).
101101

102-
TODO: FunctionN are SAM
102+
With the use of default methods, Scala's built-in `FunctionN` traits are compiled to SAM interfaces. This allows creating Scala functions from Java using Java's lambda syntax:
103103

104-
TODO: improved param type inference
104+
public class A {
105+
scala.Function1<String, String> f = s -> s.trim();
106+
}
107+
108+
Specialized function classes are also SAM interfaces and can be found in the package `scala.runtime.java8`.
109+
110+
Thanks to an improvement in type-checking, the parameter type in a lambda expression can be omitted even when the invoked method is overloaded (see [#5307](https://github.com/scala/scala/pull/5307)). In the following example, the compiler infers parameter type `Int` for type checking the lambda:
111+
112+
scala> trait MyFun { def apply(x: Int): String }
113+
114+
scala> object T {
115+
| def m(f: Int => String) = 0
116+
| def m(f: MyFun) = 1
117+
| }
118+
119+
scala> T.m(x => x.toString)
120+
res0: Int = 0
121+
122+
Note that both methods are applicable, and overloading resolution selects the one with the `Function1` argument type, as [explained in more detail below](#sam-conversion-in-overloading-resolution).
105123

106124
#### Java 8-style bytecode for lambdas
107125

0 commit comments

Comments
 (0)