Why and when to use @JvmStatic in Kotlin companion objects?
Hi everyone! I started learning Kotlin and am rewriting an old Java project. I encountered an unclear situation with companion objects.
I have this Kotlin code:
```kotlin
class MyUtils {
companion object {
fun formatDate(date: Date): String {
// date formatting
return SimpleDateFormat("yyyy-MM-dd", Locale.US).format(date)
}
const val MAX_COUNT = 100
}
}
```
From Java code, I'm trying to call this method like this:
```java
String formatted = MyUtils.formatDate(new Date());
```
But the compiler gives an error! I have to write `MyUtils.Companion.formatDate(...)`, which looks terrible. I've read about the `@JvmStatic` annotation, but I don't fully understand:
1. Why does Kotlin behave this way? In Java, I could just call st
No answers yet.
Log in to leave an answer
Blogs