You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: hand-written.md
+21-3Lines changed: 21 additions & 3 deletions
Original file line number
Diff line number
Diff line change
@@ -80,7 +80,7 @@ Note that the compiler still has quite a bit of magic to perform behind the scen
80
80
81
81
#### Lambda syntax for SAM types
82
82
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:
84
84
85
85
scala> val runRunnable: Runnable = () => println("Run!")
@@ -99,9 +99,27 @@ Note that only lambda expressions are converted to SAM type instances, not arbit
99
99
100
100
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).
101
101
102
-
TODO: FunctionNare 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:
103
103
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).
0 commit comments