I have following code in my spring cloud application :
@EnableBinding(Source.class)
@SpringBootApplication
public class dataflow_producer {
static SimpleDateFormat dateFormatter = new SimpleDateFormat("hh:mm:ss");
public static void main(String[] args) {
SpringApplication.run(dataflow_producer.class, args);
}
@Bean
@InboundChannelAdapter(value = Source.OUTPUT)
public MessageSource<String> timerMessageSource() {
return ()-> new GenericMessage<String>(dateFormatter.format(new Date()));
}
}
My question is, how this statement works ? :
return ()-> new GenericMessage<String>(dateFormatter.format(new Date()));
Does it retype object like so ? :
return (MessageSource<String>)new GenericMessage<String>(dateFormatter.format(new Date()));
Can you explain meaning of return ()->
? Why is it valid in this case ? Input is Object
of type GenericMessage<T>
, but output is Object
of type MessageSource<T>
?
Can mentioned return
statement be rewritten to non-lambda code ?
I don't know Spring.
Though, in Java 8. When you got a SAM interface (Single abstract method). Called for exemple "SAMInterface".
public interface SAMInterface {
void theSAMMethod();
}
If you need to return an object of type "SAMInterface", these code are equivalent:
SAMInterface toReturn = () -> println("Hello World!");
and
SAMInterface toReturn = new SAMInterface() {
public void theSAMMethod() {
println("Hello World!");
}
}
So if MessageSource<T>
interface has exactly 1 method to redefine.
You can use lambda :)