Loading...
Home
  • Tech Blogs
  • Videos
  • Conferences
    • Droidcon News
    • Upcoming Conferences
    • Become a Partner
    • Past Events
    • Keep Me Informed
    • Diversity Scholarships
  • Community
    • droidcon Team
    • How to Hold a Droidcon
  • Android Careers
Sign In

Global CSS

 

Explore Kotlin Annotations

Kotlin annotations which help in programming with Java

 

 
Shalu T D
Android Engineer | Blogger | Mentor | https://www.linkedin.com/in/shalutd/
Published: December 02, 2020
Tweet
Share
 

 

This article discusses the Kotlin annotations used while developing the Android app. Here we will explore the annotations @JvmStatic, @JvmOverloads, and @JvmField.

As Google suggests Kotlin as the official language for Android development, most of the people are in the process of migrating existing Java code to Kotlin code. But we can’t convert all source code from Java to Kotlin in a single sprint itself.

So, we want to convert some part of the code (Classes, enums, etc) to Kotlin and mix with the existing java code. If you are in this process, you should know these annotations.

 

@JvmStatic

In Kotlin, the package-level functions are represented as static methods. Also, in Kotlin, you can make static methods for functions that are defined in some companion object or named object by using the @JvmStatic annotation.

 

@Target([AnnotationTarget.FUNCTION, AnnotationTarget.PROPERTY, AnnotationTarget.PROPERTY_GETTER, AnnotationTarget.PROPERTY_SETTER])
annotation class JvmStatic

 

It specifies that an additional static method needs to be generated from this element if it’s a function. If this element is a property, additional static getter/setter methods should be generated.

Consider the below class:

 

class ClassName {companion object {
        @JvmStatic
        fun iAmStatic() {
            //body of Static function
        }        fun iAmNonStatic() {
            //body of Non static function
        }
    }
}

 

Here, iAmStatic() is a static function and iAmNonStatic() is a non-static function. Suppose you are calling the above methods from the Java class. It will behave like below:

 

ClassName.iAmStatic(); // works fine
ClassName.iAmNonStatic(); // compile error 
ClassName.Companion.iAmStaticMethod(); // works fine
ClassName.Companion.iAmNonStaticMethod(); // other way to work

 

As for the case of named objects, the same procedure is applicable:

 

object ObjectName {
    @JvmStatic fun iAmStatic() {
        //body of Static function
    }
    fun iAmNonStatic() {
        //body of Non static function
    }
}

 

Call the above methods from Java as below:

 

ObjectName.iAmStatic(); // works fine
ObjectName.iAmNonStatic(); // compile error
ObjectName.INSTANCE.iAmStatic(); // works
ObjectName.INSTANCE.iAmNonStatic(); // works

 

@JvmOverloads

 

@Target([AnnotationTarget.FUNCTION, AnnotationTarget.CONSTRUCTOR]) annotation class JvmOverloads

 

It instructs the Kotlin compiler to generate overloads for this function that substitute default parameter values. If a method has N parameters and M of which have default values, M overloads are generated: the first one takes N-1 parameters (all but the last one that takes a default value), the second takes N-2 parameters, and so on.

Consider a class having two fields, one is initialized and the other is not initialized.

 

data class Customer( val name: String, val dob: Date = Date())

 

Here in this class, by default, the current date will be taken as the date of birth of the customer if we are not passing the second argument while creating the customer object. So, if we are calling from Kotlin, the following code will run without any compile error.

 

val custOne = Customer("Don")
val custTwo = Customer("Don", Date())

 

But if we are calling the same from the Java then you have to pass all the parameters otherwise you will get a compile error:

 

Customer custOne = new Customer("Don"); //Here we are passing only      one argument, so we will get compile errorCustomer custTwo = new Customer("Don", new Date());//No error

 

In order to make use of the default value while creating an object from Java, we can use the annotation @JvmOverloads. Now, after using the annotation, the Kotlin code will be:

 

Customer @JvmOverloads constructor( val name: String, val dob: Date = Date())

 

Now, calling from Java, you don’t need to pass all the parameters:

 

Customer custOne = new Customer("Don"); //No Error
Customer custTwo = new Customer("Don", new Date());//No error

 

@JvmField

 

@Target([AnnotationTarget.FIELD]) annotation class JvmField

 

It instructs the Kotlin compiler not to generate getters/setters for this property and expose it as a field.

Consider the below Java class:

 

public class Customer {
    public String name;
    public Date dob;
    
    public getName() {
        return this.name;
    }    public getDob() {
        return this.dob;
    }
}

 

The corresponding Kotlin code will be as below :

 

data class Customer( val name: String, val dob: Date = Date())

 

If you are accessing the properties of the class, then the code in Kotlin is:

 

val customer = Customer("Don", Date())
val name = customer.name
val dob = customer.dob

 

But in Java, we have to use the getter method as below:

 

Customer customer = new Customer("Don", new Date());
String name = customer.getName();
Date dob = customer.getDob();

 

If you want a particular field to be used as a normal field and not as a getter or setter then you have to tell the compiler not to generate any getter and setter for the same and this can be achieved by using the @JvmField annotation. So, the Kotlin code after using the @JvmField annotation will be:

 

data class Customer(@JvmField val name: String, val dob: Date = Date())

 

Now, you can access the field from Java as below:

 

Customer customer = new Customer("Don", new Date());
String name = customer.name;

 

And you are ready to go. Thanks for reading!

Reference:

 

Calling Kotlin from Java

Kotlin code can be easily called from Java. For example, instances of a Kotlin class can be seamlessly created and…

kotlinlang.org

 

 

Tags: Android App Development, Android, Kotlin, Mobile App Development, Life

 

 

View original article at: 


 

Originally published: November 16, 2020

Android News
Evolution of Android Update SystemEvolution of Android Update System
Evolution of Android Update SystemEvolution of Android Update System

By Ivan Kuten

So, how can you update Android on mobile devices? While developing software for Smart TVs and Android-based set-top boxes, we’ve narrowed it down to four ways, discarding some very exotic options:

By ProAndroidDev -
Android News
Happy Railway
Happy Railway

By Hadi Lashkari Ghouchani

This post is on the tail of Railway Oriented Programming in Kotlin by Antony Harfield. So you need to read it first and continue here. As it’s obvious I really liked it and tried it out. It needs every process have a result like

By ProAndroidDev -
Android News
Unit Tests and Concurrency
Unit Tests and Concurrency

By Stojan Anastasov

Once Retrofit added RxJava support, RxJava became my go-to concurrency framework for writing Android apps. One of the great things about RxJava is the excellent testing support. It includes TestObserver, TestScheduler, RxJavaPlugins so you can switch your schedulers in tests.

By ProAndroidDev -
Android News
When Compat libraries will not save you
When Compat libraries will not save you

By Danny Preussler

And why you should avoid using the “NewApi” suppression! The idea of “Compat” libraries was probably one of the key aspects of Android dominating the mobile space. Other than with iOS, Android users often could not update their operating system after a new version launch, simply as their phones won’t allow them to, the Android problem of fragmentation.

 

By ProAndroidDev -
droidcon News

Tech Showcases,

Developer Resources &

Partners

/portal/rest/jcr/repository/collaboration/Groups/spaces/droidcon_hq/Documents/public/home-details/EmployerBrandingHeader
EmployerBrandingHeader
https://jobs.droidcon.com/
/portal/rest/jcr/repository/collaboration/Groups/spaces/droidcon_hq/Documents/public/employerbranding/jobs-droidcon/jobs.droidcon.com
jobs.droidcon.com

Latest Android Jobs

http://www.kotlinweekly.net/
/portal/rest/jcr/repository/collaboration/Groups/spaces/droidcon_hq/Documents/public/employerbranding/kotlin-weekly/Kotlin Weekly
Kotlin Weekly

Your weekly dose of Kotlin

https://proandroiddev.com/
/portal/rest/jcr/repository/collaboration/Groups/spaces/droidcon_hq/Documents/public/employerbranding/pad/ProAndroidDev
ProAndroidDev

Android Tech Blogs, Case Studies and Step-by-Step Coding

/detail?content-id=/repository/collaboration/Groups/spaces/droidcon_hq/Documents/public/employerbranding/Zalando/Zalando
/portal/rest/jcr/repository/collaboration/Groups/spaces/droidcon_hq/Documents/public/employerbranding/Zalando/Zalando
Zalando

Meet one of Berlin's top employers

/detail?content-id=/repository/collaboration/Groups/spaces/droidcon_hq/Documents/public/employerbranding/Academy for App Success/Academy for App Success
/portal/rest/jcr/repository/collaboration/Groups/spaces/droidcon_hq/Documents/public/employerbranding/Academy for App Success/Academy for App Success
Academy for App Success

Google Play resources tailored for the global droidcon community

Follow us

Team droidcon

Get in touch with us

Write us an Email

 

 

Quicklinks

> Code of Conduct

> Terms and Conditions

> How to hold a conference

> FAQs

> Imprint

Droidcon is a registered trademark of Mobile Seasons GmbH Copyright © 2020. All rights reserved.

powered by Breakpoint One