GNU social JP
  • FAQ
  • Login
GNU social JPは日本のGNU socialサーバーです。
Usage/ToS/admin/test/Pleroma FE
  • Public

    • Public
    • Network
    • Groups
    • Featured
    • Popular
    • People

a java sealed interface called Result that has Some and None records as implementations, with of() that returns one of the two, and allows returning an Optional for chaining the code is as follows: package com.arch.util.result; import java.util.Optional; /** * A sealed interface hierarchy to represent to existence or lack of a value, * for use in destructuring * * Returning a Result.of(value) or Result.empty() will give the ability to * destructure like: * * <pre> * if(result instanceof Some(File found)){ * // code with the found File in scope * } * </pre> * * Or * * <pre> * return switch(someOperation()){ * Some(String message) -> message; * None() -> "Nothing??"; * }; * </pre> * * Results can be used directly with {@link Optional}<T> values, present or not, * and can be easily converted to and from */ public sealed interface Result<T> permits Some, None { public static <T> Result<T> of(Optional<T> value){ return value.map(Result::of).orElseGet(Result::empty); } public static <T> Result<T> of(T value){ return value == null ? new None<>() : new Some<>(value); } public static <T> None<T> empty(){ return new None<>(); } public abstract Optional<T> toOptional(); }

Download link

https://media.chitter.xyz/media_attachments/files/111/484/341/936/988/424/original/3f22f02ca9d3dfa8.png

Notices where this attachment appears

  1. Embed this notice
    Arch 💕 (archenoth@chitter.xyz)'s status on Tuesday, 28-Nov-2023 06:15:24 JST Arch 💕 Arch 💕
    in reply to

    @technomancy partially! `Optional.ofNullable()` is an okay thing to shove returns from external libraries into, since you can then treat them the way you usually would, you can also use `.map()` instead of `.flatMap()` to call nullable methods in ways that, if they return null, still are inside Optional

    ...or you can do what i did and make a Result sealed interface that you can just say Result.of(anything), and then use it in pattern matching like Rust (or chain it into an Optional)

    In conversation Tuesday, 28-Nov-2023 06:15:24 JST from chitter.xyz permalink
  • Help
  • About
  • FAQ
  • TOS
  • Privacy
  • Source
  • Version
  • Contact

GNU social JP is a social network, courtesy of GNU social JP管理人. It runs on GNU social, version 2.0.2-dev, available under the GNU Affero General Public License.

Creative Commons Attribution 3.0 All GNU social JP content and data are available under the Creative Commons Attribution 3.0 license.