How to write following code in Kotlin for callback implementation - java

how do i write in Kotlin like java?
Callback callback= new Callback()
{
#Override
public void getCallback(ServerResponse serverResponse) {
}
}

var callback:Callback = object:Callback() {
override fun getCallback(serverResponse:ServerResponse) {
}
}
var callback:Callback says that the variable type is a Callback
object:Callback() { } is an anonymous class. It has no name when created, before being assigned to var callback. It's similar to the new Callback() code.
override replaces #Override
fun indicates that it is a function

You can use following code in Kotlin.
var callback:Callback = object:Callback() {
fun getCallback(serverResponse:ServerResponse) {
}
}
You can use this link to convert your Java code to kotlin.
https://try.kotlinlang.org

Related

Retrofit call repeats to infinite and doesn't stop

I am trying to make an API call with Retrofit 2.9.0 and use the response in a Jetpack Compose activity. The problem is that the call repeats to infinite and updates the UI on every frame. I have never used the retrofit library before so I'm sorry if the code is messy. I will attach a GIF with how the app behaves and code snippets for everything. Thanks for reading this and wanting to help. <3
What is happening in the app
Here is the class that makes the call to the API:
public class ApiHandler {
Retrofit retrofit = new Retrofit.Builder().baseUrl("https://api.quotable.io/").build();
ApiInterface apiInterface = retrofit.create(ApiInterface.class);
Call<ResponseBody> call = apiInterface.getData();
public void getQuoteRaw()
{
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
try {
MainActivityKt.getModel().setQuoteInfo(response.body().string());
} catch (IOException e)
{
e.printStackTrace();
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
System.out.println("ERROR");
}
});
}
The Interface I use to define the getData() method:
public interface ApiInterface {
#GET("random")
Call<ResponseBody> getData();
The ViewModel class for the Compose Activity:
class MainViewModel: ViewModel() {
var quoteInfo by mutableStateOf("")
The Jetpack Compose activity:
val model = MainViewModel()
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
QuoteappTheme {
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colors.background
) {
Greeting()
}
}
}
}
}
#Composable
fun Greeting(viewModel: MainViewModel = model) {
val apihandle = ApiHandler()
apihandle.getQuoteRaw()
Text(text = viewModel.quoteInfo)
}
#Preview(showBackground = true)
#Composable
fun DefaultPreview() {
QuoteappTheme {
Greeting()
}
}

How to implement a Scala Trait in Java code

In scala, there is a trait like
trait Client {
def get(requests: Seq[Request]): Future[Seq[Response]]
}
How to implement the class in Java with some fake implementation like return Future.successful(List.empty())?
I tried
class KVClient implements Client {
#Override
public Future<Seq<Response>> get(Seq<Request> requests) {
return Future.successful(List.empty());
}
But it didn't compile. Error is "KVClient is not abstract and does not override abstract method get(Seq) in Client"
if i understood you correctly you are trying to return result or error of response future.
Simple solution would be:
public CompletableFuture<Optional<?>> send() throws ExecutionException, InterruptedException {
final CompletableFuture<Optional<?>> optionalCompletableFuture = CompletableFuture.supplyAsync(() -> "")
.thenApplyAsync(f -> {
if (isError(f)) {
return Optional.empty();
}
return Optional.of(f);
});
return optionalCompletableFuture;
}

Call Kotlin function with Lambda parameters in Java

How do I call Kotlin functions with lambdas in the parameter from a Java class.
Example
fun getToken(
tokenUrl: String,
onSuccess: (String) -> Unit,
onError: (Error) -> Unit
): Provider {
//Implementation
}
You can do this
value.getToken("url",
new Function1<String, Unit>() {
#Override
public Unit invoke(String s) {
/* TODO */
return Unit.INSTANCE;
}
}, new Function1<Throwable, Unit>() {
#Override
public Unit invoke(Throwable throwable) {
/* TODO */
return Unit.INSTANCE;
}
});
You can call it with normal Java 8 lambdas, since Kotlin is actually using a single-method interface on the backend.
myFoo.getToken(tokenUrl, successString -> { ... }, error -> { ... });
This is for calling it within Kotlin, the question was edited to say "from Java" after I provided my answer. Leaving it here anyway in hope that it is useful.
You can call it like this
fun test() {
getToken("asdf", { print(it) }, { println(it) })
getToken("asdf", { print(it) }) { err -> println(err) }
getToken("asdf", ::println, ::println)
getToken("asdf", ::println) { println(it) }
}

Porting Java to C# for Xamarin Android Library

I created an Android Binding Library for my Xamarin project, using an AAR.
I am now trying to implement that library.
Here is the java snippet of code using the library:
The java code:
new AsyncOperation.CompletionHandler<RouteManager>(){
#Override
public void success(RouteManager result){
result.subscribe(ACCEL_DATA, new RouteManager.MessageHandler(){
#Override
public void process(Message message){
Log.i(LOG_TAG,message)
}
}
}
I am trying to port this code to C#.
My C# code, from C# wrapper created from binding library:
class AsyncOperationHandler : AsyncOperationCompletionHandler
{
public override unsafe void Success(Object p0)
{
try
{
var routeManger = (IRouteManager)p0;
routeManger.Subscribe(ACCEL_DATA, new RouteMessageHandler());
}
catch (Exception)
{
Log.Error(LOG_TAG, "Error");
}
}
}
class RouteMessageHandler : IRouteManagerMessageHandler
{
public void Dispose()
{
throw new NotImplementedException();
}
public IntPtr Handle { get; }
public void Process(Message p0)
{
var message = p0;
Log.Info(LOG_TAG, message);
}
}
I am getting an error in the C# wrapper on the routeManger.Subscribe line.
When the RouteManagerMessageHandler gets initialized, it gets the Handle, then throws a null pointer exception inside the Binding Library.
Is this the correct way to port a Java Interface to C#?
If you implement a Java Interface, you have to derive from Java.Lang.Object.
class RouteMessageHandler : Java.Lang.Object, IRouteManagerMessageHandler
{
public void Process(Message p0)
{
var message = p0;
Log.Info(LOG_TAG, message);
}
}
There should be something on the compile output.
Type 'AppXYZ.RouteMessageHandler' implements IRouteManagerMessageHandler but does not inherit from Java.Lang.Object. It is not supported.

Can a Groovy closure extend an abstract class

I have an abstract Java class that needs to have one method onMessage to be implemented. I know that a closure can easily implement a Java interface using the as keyword, but how can it extend an abstract Java class?
If it can't extend it, then whats the best work around possible in such cases in Groovy?
Here is my usage in Java, I am looking for something similar that can be done in Groovy.
MessageCallback callback = new MessageCallback() {
#Override
public void onMessage(Message message) {
dosomething();
}
};
Where message callback is my abstract class which I would like to use in a similar fashion in Groovy.
I believe you should be able to do:
def callback = [ onMessage:{ message -> doSomething() } ] as MessageCallback
Does that not work?
Edit
To make a call from the Map method back to the Abstract class, the only way I can find to do it is:
// Dummy class for testing
abstract class MessageTest {
abstract void onMessage( msg ) ;
void done() { println "DONE!" }
}
// Create a Proxied instance of our class, with an empty onMessage method
def p = [ onMessage:{ msg -> } ] as MessageTest
// Then overwrite the method once we have access to the Proxy object p
p.metaClass.onMessage = { msg -> println msg ; p.done() }
// Test
p.onMessage( 'woo' )
Yo can do this:
Implements a method in any class:
public MessageTest messageTest(Closure callback) {
return new MessageTest() {
#Override
public void onMessage(Message message) {
callback.call(message)
}
}
}
In main class in main method:
def outerMessage
MessageTest messageTest = messageTest() {message ->
outerMessage = message
println "innerMessage: $message"
}
messageTest.onMessage("This is the message...")
println "outerMessage: $outerMessage"
Your output should show this:
innerMessage: This is the message...
outerMessage: This is the message...
Basing on #tim_yates, here is a version of method which creates object of an abstract class from a closure. I needed something like that to be able instantiate such object in just one line.
// Dummy class for testing
abstract class MessageTest {
abstract void onMessage( msg ) ;
void done() { println "DONE!" }
}
MessageTest createMessageTest(Closure closure) {
// Create a Proxied instance of our class, with an empty onMessage method
def p = [ onMessage:{ msg -> } ] as MessageTest
// Then overwrite the method once we have access to the Proxy object p
p.metaClass.onMessage = closure
return p
}
// Create
MessageTest mt = createMessageTest { msg ->
println msg ;
done()
}
// Test
mt.onMessage( 'woo' )

Categories