Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

314
Visualizações
Runnable as method reference

Why doesn't this code compile ? Unable to grasp nuances java method reference completely :(

public class TestClass {

    static void println() {}
    
   public static void main(String[] args) {

        Runnable r1 = () -> System.out::println; // compilation error
        Runnable r2 = () -> TestClass::println;  // compilation error
        Runnable r2 = () -> System.out.println("Hello World");  // This is fine !!

    }
}
over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

There's a bit of misunderstanding here, and other answers only provide final result. So here's a real explanation.

In java, there are lambdas (() -> something), and method references (Class::method). They're basically the same thing, just with different (shorter) syntax. You can mix lambdas and method references, if you'd like (lambda in a lambda, method reference in a lambda). As long as everything is a correct type, you're ok.

So System.out::println is a method reference of type Consumer<String>, cause System.out.println() takes String as argument, and returns void - that's Consumer<String>. (There is also System.out.println() that takes no arguments, in that case it'd be a Runnable)

Runnable is a bit different because it doesn't receive any argument or returns a value. Example could be List::clear.

As to why your code was a compilation error:

When declaring a Runnable as lambda, you have to receive no arguments and return void. This lambda: Runnable r1 = () -> System.out::println; doesn't match the criteria, because it does receive no arguments (() ->), but it's expression does return a type - Consumer<String> (or Runnable again), not a void. It could be a valid Runnable if you managed to return nothing, like

Runnable r1 = () ->  {
  Consumer<String> str1 = System.out::println; // either this
  Runnable str2 = System.out::println; // or this
  return; // return type - void
}

But that kinda doesn't make sense.

So you can see clearly, that () -> System.out::println() is actually a lambda that supplies Runnable or Consumer<String>, so it's type should be

Supplier<Runnable> s = () -> System.out::println; // either this
Supplier<Consumer<String>> s = () -> System.out::println; // or this

To use it directly, you'd just have to ditch the Supplier<>

Runnable s = System.out::println; // either this
Consumer<String> s = System.out::println; // or this

How about you just explain what you're trying to do, and we'll help you.

over 4 years ago · Santiago Trujillo Relatório

0

It should be a "direct" method reference, not a supplier of something represented by a method reference.

Runnable r1 = System.out::println;
Runnable r2 = TestClass::println;

Compare

Supplier<Runnable> a = () -> System.out::println;

with

Runnable b = System.out::println;
over 4 years ago · Santiago Trujillo Relatório

0

This is not how method references work. You use them like so:

Runnable r1 = System.out::println;
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda