I tried to make Java Optional and guard clause coexist

The problem is that Java SE 8 Optional is incompatible with the guard clause, I wondered if it could coexist with the guard clause.

package com.ikemo3;

import java.util.Optional;

public class Main {

    public static void main(String[] args) {
        System.out.println(Main.sqrt("16"));
        System.out.println(Main.sqrt("-16"));
        System.out.println(Main.sqrt("str"));
    }

    public static String sqrt(String str) {
        return Optionals.of(str, String.class)
                .guard((s) -> toInteger(s), () -> "Not an integer")
                .guard((i) -> sqrt(i), () -> "Not a positive number")
                .get((d) -> String.valueOf(d));
    }

    /**
     *If the value is positive, make it an integer
     */
    public static Optional<Integer> toInteger(String str) {
        try {
            return Optional.of(Integer.valueOf(str));
        } catch (NumberFormatException e) {
            return Optional.empty();
        }
    }

    /**
     *If the value is positive, take the square root
     */
    public static Optional<Double> sqrt(int i) {
        if (i >= 0) {
            return Optional.of(Math.sqrt(i));
        } else {
            return Optional.empty();
        }
    }
}

The output result is as follows.

4.0
Not a positive number
Not an integer

How to call is like this. I wonder if it looks like a guard clause.

    public static String sqrt(String str) {
        return Optionals.of(str, String.class)
                .guard((s) -> toInteger(s), () -> "Not an integer")
                .guard((i) -> sqrt(i), () -> "Not a positive number")
                .get((d) -> String.valueOf(d));
    }

The implementation of the class is as follows.

package com.ikemo3;

import java.util.Optional;
import java.util.function.Function;
import java.util.function.Supplier;

public class Optionals<IN, RET> {
    private final IN value;
    private final RET elseValue;
    private final Class<RET> clazz;

    public static <IN, OUT> Optionals<IN, OUT> of(IN value, Class<OUT> clazz) {
        return new Optionals(value, clazz);
    }

    private Optionals(IN value, Class<RET> clazz) {
        this.value = value;
        this.clazz = clazz;
        this.elseValue = null;
    }

    private Optionals(RET elseValue) {
        this.value = null;
        this.clazz = null;
        this.elseValue = elseValue;
    }

    public <OUT> Optionals<OUT, RET> guard(Function<IN, Optional<OUT>> func, Supplier<RET> elseValue) {
        if (this.elseValue != null) {
            return new Optionals(this.elseValue);
        }

        Optional<OUT> result = func.apply(this.value);
        if (result.isPresent()) {
            return Optionals.of(result.get(), this.clazz);
        } else {
            return new Optionals(elseValue.get());
        }
    }

    public RET get(Function<IN, RET> func) {
        if (this.elseValue != null) {
            return this.elseValue;
        } else {
            return func.apply(this.value);
        }
    }
}

Recommended Posts

I tried to make Java Optional and guard clause coexist
I tried to summarize the basics of kotlin and java
I want to make a list with kotlin and java!
I want to make a function with kotlin and java!
I tried to interact with Java
I tried to summarize Java learning (1)
I tried to understand nil guard
I tried to make a client of RESAS-API in Java
I tried to summarize Java 8 now
Easy to make LINE BOT with Java Servlet Part 2: I tried image messages and templates
I tried to make an Android application with MVC now (Java)
I tried to summarize the methods of Java String and StringBuilder
[Java] I tried to make a maze by the digging method ♪
I tried to summarize Java lambda expressions
I tried to make my own transfer guide using OpenTripPlanner and GTFS
I made a virtual currency arbitrage bot and tried to make money
I tried to make a talk application in Java using AI "A3RT"
java I tried to break a simple block
I tried to link grafana and postgres [docker-compose]
I did Java to make (a == 1 && a == 2 && a == 3) always true
I tried to implement deep learning in Java
I wanted to make (a == 1 && a == 2 && a == 3) true in Java
I tried to output multiplication table in Java
I tried to link JavaFX and Spring Framework.
I tried to create Alexa skill in Java
I tried to break a block with java (1)
A story when I tried to make a video by linking Processing and Resolume
[Small story] I tried to make the java ArrayList a little more convenient
I tried Mastodon's Toot and Streaming API in Java
I tried to read and output CSV with Outsystems
I tried to implement TCP / IP + BIO with JAVA
I tried to implement Firebase push notification in Java
[Java 11] I tried to execute Java without compiling with javac
[Java] I tried to solve Paiza's B rank problem
I tried to operate SQS using AWS Java SDK
# 2 [Note] I tried to calculate multiplication tables in Java.
I started MySQL 5.7 with docker-compose and tried to connect
I tried to integrate AWS I oT button and Slack
I tried to create a Clova skill in Java
I tried to make FizzBuzz that is uselessly flexible
I tried to implement Stalin sort with Java Collector
I want to transition screens with kotlin and java!
[Java] I tried to implement Yahoo API product search
I tried to implement the Euclidean algorithm in Java
~ I tried to learn functional programming in Java now ~
I used to make nc (netcat) with JAVA normally
I tried to chew C # (reading and writing files)
I tried to find out what changed in Java 9
I tried to make an introduction to PHP + MySQL with Docker
I tried to create a java8 development environment with Chocolatey
I tried to modernize a Java EE application with OpenShift.
Java --How to make JTable
I tried to collect and solve Ruby's "class" related problems.
[JDBC] I tried to access the SQLite3 database from Java.
How to use java Optional
I tried to verify this and that of Spring @ Transactional
I just wanted to make a Reactive Property in Java
I tried Drools (Java, InputStream)
I tried using Hotwire to make Rails 6.1 scaffold a SPA
I tried to summarize personally useful apps and development tools (development tools)
[Java] I tried access modifier public and unspecified field access [Eclipse]