Static methods and variables in Kotlin: how to replace Java static?
Hello! I'm switching from Java to Kotlin and ran into a problem. In Java, I often used static methods and variables for utility classes, constants, or factory methods. For example, here's a simple class in Java:
```java
public class MathUtils {
public static final double PI = 3.14159;
public static double square(double x) {
return x * x;
}
}
```
I tried to write the same thing in Kotlin, but the compiler gives an error when trying to use the `static` keyword. I've read that Kotlin doesn't have `static` as such, but there are some "companion objects". I tried:
```kotlin
class MathUtils {
companion object {
val PI = 3.14159
fun square(x: Double): Double = x * x
}
}
```
This works, but I'm confused by a few things