In this meta post, it's decided that function literals are valid when a function is required.
What about lambda expressions in Java 8? These are similar to function literals in other languages, but aren't really the same thing. Actually, these can be used in place of an instance of a functional interface.
For example, to remove the first character of a string:
String f(String s){return s.substring(1);} // standard method syntax
Function<String,String> f = s -> s.substring(1); // lambda expression to define function
Object o = (Function<String,String>) s -> s.substring(1); // works
Object o = s -> s.substring(1) // compile-time error: Object not a functional interface
Since almost any normal expression can be assigned to an Object
, this seems to show that s->s.substring(1)
isn't really an instance of a function, but rather syntax that resolves to a function.
interface I {
public static void main(String[] args) {
System.out.println("Hello");
}
String foo(String s);
}
class C {
I i = s -> s.substring(1);
}
In this code, the interface I
is actually a runnable program. So when s->s.substring(1)
is assigned to a variable of type I
, it's not clear if this is a function.
Anyway, I'm not really sure about whether these expressions should count as functions. What do you think?