Why do we use “companion object” as a kind of replacement for Java static fields in Kotlin?

What is the intended meaning of “companion object”? Why is it called “companion”? First, Kotlin doesn’t use the Java concept of static members because Kotlin has its own concept of objects for describing properties and functions connected with singleton state, and Java static part of a class can be elegantly expressed in terms of singleton: … Read more

Cross references in type parameters

Kotlin doesn’t have raw types, you cannot just drop the type parameters. One option similar to raw types is to use star projections: abstract class Element<S : Snapshot<*>> { /* … */ } abstract class Snapshot<E : Element<*>> { /* … */ } But you won’t be able to normally work with the type parameters … Read more

how to run compiled class file in Kotlin?

Knowing the Name of Your Main Class Currently (Kotlin since M14 including up to 1.0 betas), to run a Kotlin class you are actually running a special class that is created at the file level that hold your main() and other functions that are top-level (outside of a class or interface). So if your code … Read more

How to clone object in Kotlin?

For a data class, you can use the compiler-generated copy() method. Note that it will perform a shallow copy. To create a copy of a collection, use the toList() or toSet() methods, depending on the collection type you need. These methods always create a new copy of a collection; they also perform a shallow copy. … Read more