Skip to content

Instantly share code, notes, and snippets.

@momvart
Created November 24, 2021 16:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save momvart/2f052ecdb2291b4a231cc295d7b9d0f0 to your computer and use it in GitHub Desktop.
Save momvart/2f052ecdb2291b4a231cc295d7b9d0f0 to your computer and use it in GitHub Desktop.
A set of extensions functions written on object, by default available in Kotlin, ported for c#.
using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
namespace Utilities
{
public static class KotlinObjectExtensions
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static T Also<T>(this T callee, Action<T> action)
{
action(callee);
return callee;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static async Task<T> Also<T>(this T callee, Func<T, Task> action)
{
await action(callee);
return callee;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static TResult Let<T, TResult>(this T callee, Func<T, TResult> func) =>
func(callee);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static async Task<TResult> Let<T, TResult>(this T callee, Func<T, Task<TResult>> func) =>
await func(callee);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Let<T>(this T callee, Action<T> func) =>
func(callee);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static async Task Let<T>(this T callee, Func<T, Task> func) =>
await func(callee);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static T? TakeIf<T>(this T callee, Func<T, bool> predicate) =>
predicate(callee) ? callee : default;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static async Task<T?> TakeIf<T>(this T callee, Func<T, Task<bool>> predicate) =>
await predicate(callee) ? callee : default;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static T? TakeIf<T>(this T callee, bool condition) =>
condition ? callee : default;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment