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

Kotlin Ternary Conditional Operator

In Kotlin, if statements are expressions. So the following code is equivalent: if (a) b else c The distinction between expression and statement is important here. In Java/C#/JavaScript, if forms a statement, meaning that it does not resolve to a value. More concretely, you can’t assign it to a variable. // Valid Kotlin, but invalid … Read more

What does .() mean in Kotlin?

Quick answer block: SCRIPT.() -> Unit = {} This represents a “function literal with receiver”. It’s a function parameter with a function type () -> Unit and SCRIPT as it’s receiver. Function Literals/Lambda with Receiver Kotlin supports the concept of “function literals with receivers”. It enables the access on visible methods and properties of a … Read more

How does erasure work in Kotlin?

Actually Kotlin knows the difference between the two methods in your example, but jvm will not. That’s why it’s a “platform” clash. You can make your second example compile by using the @JvmName annotation: class Foo { @JvmName(“barString”) fun bar(foo: List<String>): String { return “” } @JvmName(“barInt”) fun bar(foo: List<Int>): String { return “2”; } … Read more

Kotlin data class: how to read the value of property if I don’t know its name at compile time?

Here is a function to read a property from an instance of a class given the property name (throws exception if property not found, but you can change that behaviour): import kotlin.reflect.KProperty1 import kotlin.reflect.full.memberProperties @Suppress(“UNCHECKED_CAST”) fun <R> readInstanceProperty(instance: Any, propertyName: String): R { val property = instance::class.members // don’t cast here to <Any, R>, it … Read more

Building a self-executable JAR with Gradle and Kotlin

Add the plugin application, then set the mainClassName as mainClassName=”[your_namespace].[your_arctifact]Kt” For instance, suppose you have placed the following code in a file named main.kt: package net.mydomain.kotlinlearn import kotlin import java.util.ArrayList fun main(args: Array<String>) { println(“Hello!”) } your build.gradle should be: apply plugin: ‘kotlin’ apply plugin: ‘application’ mainClassName = “net.mydomain.kotlinlearn.MainKt” In fact Kotlin is building a … Read more