@JvmStatic, @JvmField and @JvmOverloads

Kotlin language Mid-level Kotlin 2.0+ API 24+ Reviewed By Best Latest Apps

Pick the fix

Java code must call Prices.format(1.5) as a static method. What do you add?

class Prices {
    companion object {
        fun format(value: Double): String = "€%.2f".format(value)
    }
}
Options
Hint 1 of 1

How does Java see companion functions by default?

Choose an answer, then open Show answer below to check it.

Show answer

Answer: A @JvmStatic on the function inside the companion object

Correct. Without it, Java has to call Prices.Companion.format.

Why not the others?
  • B @JvmField. That's for properties, not functions.
  • C @JvmOverloads. That generates overloads for default arguments.
  • D const. const applies to properties with constant values.

30-second answer

They shape how Kotlin code looks to Java callers. @JvmStatic on a companion or object member generates a real static method. @JvmField exposes a property as a public field with no getter or setter. @JvmOverloads generates Java overloads for a function or constructor with default arguments, which custom Views need.

Practise saying it · 30 s. No recording, just a timer

Explain @JvmStatic, @JvmOverloads and @JvmField.

Say your answer out loud, then check which of these points you covered:

  • @JvmStatic for static methods
  • @JvmField for public fields
  • @JvmOverloads for default args
  • Common in custom Views

Deep dive

A custom View written in Kotlin uses @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0).

const val is already a static field; @JvmField is for non-const values.

@JvmName renames the generated method, for example to avoid signature clashes.

@Throws declares checked exceptions so Java callers can catch them.

A custom View constructor Compile-checked · Kotlin 2.4.21
class BadgeView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr)

Common mistakes

  • Adding @JvmField to a property with a custom getter, which isn't allowed.
  • Using @JvmOverloads with defStyleAttr = 0 when extending a styled widget like Button, and losing its theme style.
  • Adding these annotations where no Java code calls the API.

Senior take & follow-ups

Mention the custom View constructor; it's the most common real case.

Follow-up questions

Think of your answer first, then open the hint.

  1. Why does @JvmOverloads matter for Views?

    Show hint

    The framework inflates Views from XML by calling the two-argument constructor.

  2. What does @Throws do?

    Show hint

    Adds a throws clause so Java must handle the exception.

Suggest a fix if something here is wrong or out of date.