I've been trying to use my Android Library (written in Kotlin) in a Xamarin project but I'm stuck in passing Lambda functions to C# generated code of Kotlin
I'm trying to do something like this
client.DoSomething((response) => {}, (error) => {});
But I'm getting this error
CS1660: Cannot convert lambda expression to type 'IFunction1' because it is not a delegate type
This is the generated C# code for my library for this specific function
using Android.Runtime;
using Java.Interop;
using Java.Lang;
using Kotlin.Jvm.Functions;
using System;
[Register ("doSomething", "(Lkotlin/jvm/functions/Function1;Lkotlin/jvm/functions/Function1;)V", "")]
public unsafe void DoSomething (IFunction1 onSuccess, IFunction1 onFailure);
What's the correct way of doing this?
I'm using this class in order to adapt the Function1 exported by a Kotlin Binding to C# Lambda:
class Function1Impl<T> : Java.Lang.Object, IFunction1 where T : Java.Lang.Object
{
private readonly Action<T> OnInvoked;
public Function1Impl(Action<T> onInvoked)
{
this.OnInvoked = onInvoked;
}
public Java.Lang.Object Invoke(Java.Lang.Object objParameter)
{
try
{
T parameter = (T)objParameter;
OnInvoked?.Invoke(parameter);
return null;
}
catch (Exception ex)
{
// Exception handling, if needed
}
}
}
Using this class you would be able to do the following:
client.DoSomething(new Function1Impl<ResponseType>((response) => {}), new Function1Impl<ErrorType>((error) => {}));
P.S.: ResponseType is the class of your input param response and ErrorType is the class of your input param error.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With