• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Jeanne Boyarsky
  • Devaka Cooray
  • Paul Clapham
Sheriffs:
  • Tim Cooke
  • Knute Snortum
  • Bear Bibeault
Saloon Keepers:
  • Ron McLeod
  • Tim Moores
  • Stephan van Hulst
  • Piet Souris
  • Ganesh Patekar
Bartenders:
  • Frits Walraven
  • Carey Brown
  • Tim Holloway

Throw exception if invald input

 
Ranch Hand
Posts: 72
MySQL Database AngularJS Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I want to achieve something like this in functional way. Any help ?

 
Master Rancher
Posts: 451
6
IntelliJ IDE Spring Fedora
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
looks like a lambda already
 
Marshal
Posts: 64693
225
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It isn't possible to do that in a functional way. The functional style doesn't allow side‑effects, which forbids you to throw an exception.
Maybe you could convert that to a Predicate:-
 
Saloon Keeper
Posts: 10308
217
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What is functional, according to you?

It doesn't really make sense to create a field of a functional interface. Just write it as a method, and you can just pass the method handle to whatever higher-level function you're calling.

You can also create a method that takes the length that needs to be asserted and partially applies it to create a function:

If you're looking for a way to throw the exception as part of an expression (so without using an if-statement), then I'm afraid that's not possible in Java, as of version 11.
 
Sheriff
Posts: 21759
102
Eclipse IDE Spring VI Editor Chrome Java Ubuntu Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A little off-topic, but you usually shouldn't use Void in any of the out-of-the-box functional interfaces. For most situations, there's an alternative that makes the Void superfluous. For instance, a Function<Void, X> can be replaced by a Supplier<X>, and a Function<String[], Void> by a Consumer<String[]>. The latter has as advantage that it doesn't need to return anything. Even with Void, you need to return something. Since you can't instantiate Void, that means you need to return null. By switching to a Consumer<String[]> you no longer have to, the functional interface's method already has void as return type.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!