Created
June 25, 2022 17:46
-
-
Save dimitris-papadimitriou-chr/9cd3403d42ce1ef6da593d0be5fc0cdc to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Threading.Tasks; | |
namespace FunctionalExperimentation.FuncTaskCovarinat.Minimal.DelegateAdapter | |
{ | |
public static partial class F | |
{ | |
public static FuncTask<T> ToFuncTask<T>(this Func<Task<T>> @this) => | |
new FuncTask<T>( | |
()=>@this().GetAwaiter().GetResult() | |
); | |
public static T GetOrThrowIfNull<T>(this FuncTask<T> @this, string message) | |
{ | |
var value = @this(); // this might also throw exception from Task. | |
return value ?? throw new Exception(message); | |
} | |
} | |
public interface IWithResult | |
{ | |
public bool IsSuccesfull { get; } | |
} | |
public class SomeResult : IWithResult | |
{ | |
public bool IsSuccesfull => true; | |
} | |
public class FuncTaskCovarinat | |
{ | |
public static async Task RunAsync() | |
{ | |
Func<Task<SomeResult>> GetSomethingLazyAsync() => () => Task.FromResult(new SomeResult()); | |
//Func<Task<IWithResult>> t = GetSomethingLazyAsync(); | |
//Error CS0029 Cannot implicitly convert type 'System.Func<System.Threading.Tasks.Task<FunctionalExperimentation.Practical.FuncTaskCovarinat.SomeResult>>' | |
// to 'System.Func<System.Threading.Tasks.Task<FunctionalExperimentation.Practical.FuncTaskCovarinat.IWithResult>>' | |
//ok this is covariant on T | |
FuncTask<IWithResult> lazyResult = GetSomethingLazyAsync().ToFuncTask(); | |
SomeResult result = GetSomethingLazyAsync() | |
.ToFuncTask() | |
.GetOrThrowIfNull("failed to get"); | |
} | |
} | |
public delegate T FuncTask<out T>(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment