0
0
Kotlinprogramming~20 mins

Kotlin annotations for Java callers (@JvmStatic, @JvmField) - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Kotlin Annotations for Java Callers (@JvmStatic, @JvmField)
📖 Scenario: You are creating a Kotlin class that will be used by Java code. To make the Kotlin code easier and more natural to call from Java, you will use special Kotlin annotations.These annotations help Java callers access Kotlin properties and functions as if they were regular Java static members or fields.
🎯 Goal: Build a Kotlin class with a companion object that uses @JvmStatic and @JvmField annotations so Java code can call the static function and access the field directly.
📋 What You'll Learn
Create a Kotlin class named Utils with a companion object
Inside the companion object, create a function greet that returns the string "Hello from Kotlin"
Annotate the greet function with @JvmStatic
Inside the companion object, create a constant string field VERSION with value "1.0"
Annotate the VERSION field with @JvmField
Print the result of calling Utils.greet() and the value of Utils.VERSION
💡 Why This Matters
🌍 Real World
Kotlin is often used in Android apps and backend services, but many projects still use Java. These annotations help Kotlin code work smoothly with existing Java code.
💼 Career
Understanding Kotlin-Java interoperability is important for Android developers and backend engineers working in mixed Kotlin and Java codebases.
Progress0 / 4 steps
1
Create the Kotlin class with a companion object
Create a Kotlin class called Utils with an empty companion object inside it.
Kotlin
Need a hint?
Remember, a companion object is like a static holder inside a Kotlin class.
2
Add a function with @JvmStatic annotation
Inside the companion object of Utils, create a function called greet that returns the string "Hello from Kotlin". Annotate this function with @JvmStatic.
Kotlin
Need a hint?
Use @JvmStatic just before the function declaration inside the companion object.
3
Add a constant field with @JvmField annotation
Inside the companion object of Utils, create a constant string field called VERSION with the value "1.0". Annotate this field with @JvmField.
Kotlin
Need a hint?
Use @JvmField just before the val declaration inside the companion object.
4
Print the function call and field value
Write two println statements to print the result of calling Utils.greet() and the value of Utils.VERSION.
Kotlin
Need a hint?
Call Utils.greet() and Utils.VERSION inside println to display their values.