I am writing a Javafx application in which an email is sent using JavaMail. When creating a new Session I use the syntax.
Session session = Session.getInstance(props,
//Use labmda expression?
new javax.mail.Authenticator() {
protected javax.mail.PasswordAuthentication getPasswordAuthentication(){
return new javax.mail.PasswordAuthentication(userName, password);
}
}
);
I was wondering if a lambda expression could be used to simplify that such as
() -> return new java.mail.PasswordAuthentiaction(userName, password)
but whenever I use that it throws Incompatible types, and says that Authenticator isn't a functional interface.
No, you can't use lambda here. Lambdas can be used only as representation of implementation of functional interface (interface with only one abstract method) but Authenticator
is not functional interface because
- it doesn't have exactly one abstract method which lambda should implement (actually it doesn't have any abstract methods)
- it is class (abstract, but still class) not interface.
So once again, lambdas can be used only with interfaces with one abstract method. This way lambda knows which method it implements (knows its signature so it knows number of required arguments, their type and type or expected returned value if any).
Also we don't say that lambdas can be used with any SAM (Single Abstract Method - like abstract classes) types, because it can be used only with SAM interfaces (functional interfaces).
In addition to the explanation for why you can't use lambdas here, note that you probably don't even need to use an Authenticator at all.