2

I am new to java 8 and I am learning method reference. I was coding and I used lambda expression in the below case. But the sonar lint says that the below lines can be further reduces by using method reference. Now I am confused about it's implemenetation as there is

  1. Typecasting
  2. I read that in method refernce should be used when we are just passing what is coming. For example o -> System.out.println(o) could be written as System.out::println Can method reference be implemented in the below case

    ExpectedCondition<Boolean> cc = (x) -> {
            JavascriptExecutor j = (JavascriptExecutor) x;
            return (Boolean) j.executeScript("return document.readyState").toString().equals(completeString);
        };
    
Holger
  • 285,553
  • 42
  • 434
  • 765
BeginnersSake
  • 650
  • 2
  • 18
  • 30
  • See [my answer here](http://stackoverflow.com/a/32332582/2071828) about using method references for calls with parameters. – Boris the Spider Jan 25 '17 at 10:11
  • Should it be `.equals(x)` instead of `.equals(completeString)`? – Andreas Lundgren Jan 25 '17 at 10:14
  • @AndreasLundgren It is comepleteString that is a separate string – BeginnersSake Jan 25 '17 at 10:14
  • @BoristheSpider x is WebDriver's reference and j = (JavascriptExecutor) x; – BeginnersSake Jan 25 '17 at 10:16
  • 3
    @BeginnersSake of course, sorry - being stupid. Completely missed the cast there... You can use a chain of `Function.compose` to do the various operations. I don't see that as an improvement however. As a matter of coding style, I require multiline lambdas moved into a well named method where appropriate; but other than that I would leave this code be. – Boris the Spider Jan 25 '17 at 10:18
  • 4
    It can be reduced to expression form: `ExpectedCondition cc = (x) -> ((JavascriptExecutor)x).executeScript("return document.readyState").toString() .equals(completeString);` but not to a method reference (unless you create a dedicated method containing that code, but that’s not a simplification, it’s exactly what a lambda expression does for you). – Holger Jan 25 '17 at 10:21

1 Answers1

1
Boolean fun(WebDriver d)
    {
        JavascriptExecutor j = (JavascriptExecutor) d;
        return (Boolean) j.executeScript("return document.readyState").toString().equals("");
    }
ExpectedCondition<Boolean> cd = this::fun; 
BeginnersSake
  • 650
  • 2
  • 18
  • 30