### JUnit Assertions for Result and Option in Java Source: https://context7.com/dzikoysk/expressible/llms.txt Provides JUnit 5 test examples demonstrating assertions for Result and Option types using Expressible's assertion utilities. These assertions help verify success, failure, defined, and empty states of Result and Option objects, improving test readability and safety. ```java import static panda.std.ResultAssertions.*; import static panda.std.OptionAssertions.*; import org.junit.jupiter.api.Test; class UserServiceTest { @Test void shouldCreateUserSuccessfully() { // Arrange String username = "john"; // Act Result result = userService.createUser(username); // Assert - verify success User user = assertOk(result); assertEquals("john", user.getUsername()); // Or verify exact value assertOk(expectedUser, result); } @Test void shouldFailWithDuplicateUsername() { // Arrange String username = "existing"; // Act Result result = userService.createUser(username); // Assert - verify error String error = assertError(result); assertTrue(error.contains("already exists")); // Or verify exact error assertError("User already exists", result); } @Test void shouldFindUser() { // Act Option option = userRepository.findById(123); // Assert User user = assertDefined(option); assertEquals(123, user.getId()); // Or verify exact value assertDefined(expectedUser, option); } @Test void shouldReturnEmptyForMissingUser() { // Act Option option = userRepository.findById(999); // Assert assertEmpty(option); } } ``` -------------------------------- ### Reactive References: Simple Reactivity with MutableReference and Reference Source: https://context7.com/dzikoysk/expressible/llms.txt Demonstrates the creation, subscription, and updating of reactive references using `Reference` and `MutableReference`. It covers immediate and detailed subscriptions, function-based updates, computed references from single or multiple sources, and utility operations like mapping, peeking, and conversion to `Option`. ```java import panda.std.reactive.*; import static panda.std.reactive.Reference.*; import static panda.std.reactive.MutableReference.*; // Creating references Reference immutable = reference(10); MutableReference mutable = mutableReference(5); // Subscribing to changes mutable.subscribe(newValue -> { System.out.println("Value changed to: " + newValue); }); // Detailed subscription with old and new values mutable.subscribeDetailed((oldValue, newValue) -> { System.out.println("Changed from " + oldValue + " to " + newValue); }); // Immediate subscription (fires immediately with current value) mutable.subscribe(value -> process(value), true); // Updating mutable references mutable.update(10); // Triggers subscribers mutable.update(current -> current + 5); // Function-based update // Computed references Reference doubled = mutable.computed(value -> value * 2); // Multi-source computed values Reference a = reference(1); Reference b = reference(2); Reference sum = computed( dependencies(a, b), () -> a.get() + b.get() ); sum.subscribe(value -> System.out.println("Sum: " + value)); ((MutableReference) b).update(3); // Prints: "Sum: 4" // Mapping and peeking String text = mutable.map(value -> "Value is: " + value); mutable.peek(value -> logger.debug("Current: " + value)); // Conversion Option option = mutable.toOption(); ``` -------------------------------- ### Throwing Functional Interfaces in Java Source: https://context7.com/dzikoysk/expressible/llms.txt Demonstrates the usage of Expressible's throwing functional interfaces (ThrowingFunction, ThrowingSupplier, ThrowingConsumer, ThrowingRunnable) in Java. These interfaces allow functional operations to declare checked exceptions without requiring explicit try-catch blocks, promoting cleaner code and seamless integration with Result types. ```java import panda.std.function.*; // Throwing functions ThrowingFunction parse = input -> { if (input == null) throw new IOException("Null input"); return Integer.parseInt(input); }; // Throwing suppliers ThrowingSupplier fetchData = () -> { return database.query("SELECT * FROM users"); }; // Throwing consumers ThrowingConsumer processFile = file -> { Files.write(file.toPath(), data); }; // Throwing runnables ThrowingRunnable initialize = () -> { setupResources(); connectToDatabase(); }; // Tri and Quad functions for multiple parameters TriFunction process = (name, age, active) -> createUser(name, age, active); QuadConsumer log = (user, id, action, success) -> logger.info("User " + user + " " + action); // Usage with Result Result result = Result.supplyThrowing( IOException.class, () -> parse.apply("123") ); ``` -------------------------------- ### Java Option: Enhanced Optional with Functional Composition Source: https://context7.com/dzikoysk/expressible/llms.txt Introduces an enhanced Option type in Java, offering richer functional composition and integration with other Expressible types. It supports creation, mapping, filtering, type checking, side effects, fallbacks, conversions, exception handling, and association with pairs. ```java import panda.std.Option; // Creating options Option some = Option.of("value"); Option none = Option.none(); Option conditional = Option.when(condition, "value"); // Mapping and flat mapping Option length = some.map(String::length); Option user = Option.of("john") .flatMap(username -> findUser(username)); // Filtering Option adult = Option.of(25) .filter(age -> age >= 18); // Type checking Option text = Option.of((Object) "hello") .is(String.class); // Peeking and side effects Option.of("data") .peek(value -> logger.info("Got: " + value)) .onEmpty(() -> logger.warn("No value present")); // Fallbacks and defaults String value = none .orElse("default") .orElseGet(() -> computeDefault()); User user = findUser(id) .orThrow(() -> new NotFoundException("User not found")); // Converting to other types Stream stream = some.toJavaStream(); Optional optional = some.toOptional(); Result result = some.toResult("Error message"); // Exception handling Option safe = Option.supplyThrowing(() -> { return riskyOperation(); }); // Associate with pair Option> associated = Option.of("key") .associateWith(key -> Option.of(42)); ``` -------------------------------- ### Tuple Types: Immutable Containers (Pair, Triple, Quad) Source: https://context7.com/dzikoysk/expressible/llms.txt Illustrates the usage of `Pair`, `Triple`, and `Quad` for creating immutable containers of 2, 3, or 4 values. Demonstrates creation, accessing elements, transforming tuples, extending them to larger types, and destructuring within functional operations like `PandaStream.map`. ```java import panda.std.*; // Creating pairs Pair pair = Pair.of("age", 25); String key = pair.getFirst(); Integer value = pair.getSecond(); // Transforming pairs Pair modified = pair .withFirst("name") .withSecond("John"); // Extending to triple Triple triple = pair.add(true); // Triple operations Triple t = Triple.of("user", 42, true); Quad quad = t.add("extra"); // Destructuring in functional chains PandaStream.of( Pair.of("John", 25), Pair.of("Jane", 30) ).map(pair -> pair.getFirst() + " is " + pair.getSecond()) .forEach(System.out::println); ``` -------------------------------- ### Java Result: Basic Operations and Error Handling Source: https://context7.com/dzikoysk/expressible/llms.txt Demonstrates the creation and manipulation of Result types in Java for functional error handling. It covers success/error creation, pattern matching with map/flatMap, handling results with peek/onError, fallback mechanisms with orElseGet, exception wrapping with supplyThrowing, and conditional results using when. ```java import panda.std.Result; import static panda.std.Result.*; // Basic success and error creation Result success = ok("User created successfully"); Result failure = error("Username already exists"); // Pattern matching with map and flatMap Result result = validateInput("john123") .flatMap(username -> createUser(username)) .map(user -> user.getId()) .mapErr(error -> "Failed to create user: " + error); // Handling results with peek and onError result .peek(id -> System.out.println("User ID: " + id)) .onError(err -> logger.error(err)); // Convert to value with fallback String message = result .map(id -> "Success: " + id) .orElseGet(error -> "Error: " + error); // Exception wrapping Result attempt = Result.supplyThrowing(() -> { return performRiskyOperation(); }); // Conditional results Result validated = Result.when( username.length() >= 3, () -> new User(username), () -> "Username too short" ); private Result validateInput(String input) { if (input == null || input.isEmpty()) { return error("Input cannot be empty"); } if (input.length() < 3) { return error("Input too short"); } return ok(input); } private Result createUser(String username) { if (userExists(username)) { return error("User already exists"); } return ok(new User(username)); } ``` -------------------------------- ### Kotlin Result Extensions: Idiomatic Syntax and Operations Source: https://context7.com/dzikoysk/expressible/llms.txt Provides Kotlin extension functions for the Result type, enabling natural syntax for success/error handling, unit mapping, exception throwing, and chaining operations. It simplifies common Result patterns in Kotlin. ```kotlin import panda.std.* // Extension functions for natural syntax val user: Result = User("john").asSuccess() val error: Result = "Invalid input".asError() // Unit mapping val unitResult: Result = saveUser(user) .mapToUnit() // Direct exception throwing fun getUser(id: Int): User { return findUser(id) .orThrow() // throws if Result contains error } // Success shorthand fun createEmpty(): Result = ok() // Chaining multiple operations val processed = username .asSuccess() .flatMap { validateUsername(it) } .flatMap { createUser(it) } .map { it.id } .orThrow() ``` -------------------------------- ### PandaStream: Enhanced Java Stream API with Expressible Integration Source: https://context7.com/dzikoysk/expressible/llms.txt Introduces `PandaStream`, which enhances Java's `Stream` API with support for Expressible types and additional utilities. It covers stream creation from various sources, standard stream operations like `map` and `filter`, concatenation, association, integration with `Option` and `Result`, and terminal operations. ```java import panda.std.stream.PandaStream; import panda.std.Option; import panda.std.Result; // Creating streams PandaStream empty = PandaStream.empty(); PandaStream fromList = PandaStream.of(Arrays.asList("a", "b", "c")); PandaStream fromStream = PandaStream.of(Stream.of("x", "y", "z")); // Standard stream operations PandaStream lengths = fromList .map(String::length) .filter(len -> len > 0); // Concatenation PandaStream combined = fromList .concat("d", "e", "f") .concat(Arrays.asList("g", "h")); // Association with pairs PandaStream> indexed = fromList .associateWith(1); // Integration with Option PandaStream values = PandaStream.of( Option.of("present"), Option.none(), Option.of("another") ).flatMap(opt -> opt.toStream()); // Integration with Result PandaStream successful = PandaStream.of( Result.ok(1), Result.error("failed"), Result.ok(2) ).filter(Result::isOk) .map(Result::get); // Collection List list = fromList.toList(); Set set = fromList.toSet(); Map map = fromList.toMap( s -> s, String::length ); // Terminal operations Option first = fromList.head(); Option any = fromList.findAny(); boolean hasContent = fromList.exists(s -> s.length() > 2); ``` -------------------------------- ### Java Lazy: Thread-Safe Lazy Initialization and Evaluation Source: https://context7.com/dzikoysk/expressible/llms.txt Implements thread-safe lazy initialization and evaluation for values and operations. It ensures that expensive computations are performed only once upon the first access, with support for pre-initialization, lazy runnables for side effects, state checking, and robust error handling. ```java import panda.std.Lazy; // Lazy value initialization Lazy lazy = new Lazy<>(() -> { System.out.println("Computing expensive value..."); return new ExpensiveObject(); }); // Value computed only on first access ExpensiveObject obj1 = lazy.get(); // Prints: "Computing expensive value..." ExpensiveObject obj2 = lazy.get(); // Returns cached value, no print // Pre-initialized lazy Lazy completed = new Lazy<>("Already computed"); // Lazy runnable for side effects Lazy initialize = Lazy.ofRunnable(() -> { System.out.println("One-time initialization"); setupDatabase(); }); initialize.get(); // Executes initialization initialize.get(); // Does nothing, already initialized // Checking state if (!lazy.isInitialized()) { System.out.println("Value not yet computed"); } // Error handling Lazy failing = new Lazy<>(() -> { throw new RuntimeException("Computation failed"); }); try { failing.get(); // Throws AttemptFailedException } catch (AttemptFailedException e) { System.out.println("Failed: " + e.getCause()); } System.out.println(failing.hasFailed()); // true ``` -------------------------------- ### Java Completable: Synchronized Async Value Container Source: https://context7.com/dzikoysk/expressible/llms.txt Provides a synchronized alternative to CompletableFuture, designed for value completion patterns without inherent concurrency. It supports subscribing to completion, completing values, transformation chains, flat composition, pre-completed values, state checking, exception handling, and conversion to CompletableFuture. ```java import panda.std.reactive.Completable; // Creating completable Completable completable = Completable.create(); // Subscribing to completion completable.then(value -> { System.out.println("Received: " + value); }); completable.subscribe(value -> { logger.info("Value completed: " + value); }); // Completing with value completable.complete("Hello"); // Transformation chains Completable length = completable.thenApply(String::length); Completable isEmpty = length.thenApply(len -> len == 0); // Flat composition Completable user = Completable.create(); Completable profile = user.thenCompose(u -> fetchProfile(u.getId())); // Pre-completed values Completable immediate = Completable.completed("Ready"); // Checking state if (completable.isReady()) { String value = completable.get(); } // Exception handling String safeValue = completable.orThrow(() -> new IllegalStateException("Not completed") ); // Integration with CompletableFuture CompletableFuture future = completable.toFuture(); ``` -------------------------------- ### Java Result: Advanced Functional Operations Source: https://context7.com/dzikoysk/expressible/llms.txt Illustrates advanced functional operations on Java Result types, including filtering with predicates, merging multiple results, swapping success and error types, type checking, folding both branches into a common type, exception filtering, and chaining with orElse. ```java import panda.std.Result; import static panda.std.Result.*; // Filtering with predicates Result age = ok(25) .filter(a -> a >= 18, a -> "Must be 18 or older: " + a) .filter(a -> a <= 120, a -> "Invalid age: " + a); // Merging multiple results Result firstName = ok("John"); Result lastName = ok("Doe"); Result fullName = firstName.merge( lastName, (first, last) -> first + " " + last ); // Swapping success and error types Result swapped = ok(42).swap(); // Result // Type checking and casting Result value = ok("text"); Result stringValue = value.is( String.class, v -> "Expected String but got " + v.getClass() ); // Fold both branches into common type String status = result.fold( value -> "Success: " + value, error -> "Error: " + error ); // Exception filtering Result validated = ok(new User("john")) .filterWithThrowing(user -> { if (!user.isValid()) { throw new ValidationException("Invalid user"); } }) .mapFilterError(ex -> new ValidationException("Validation failed: " + ex.getMessage())); // Chaining with orElse Result fallback = error("primary failed") .orElse(err -> ok("fallback value")); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.