Introduction to Kotlin 2

Ayako Sayama
Jul 24, 2017 · 4 min read

This is a sequel to part 1! Original article is written by my friend Hiroki, who is a senior android developer. Original article is here.

This part 2 will be about how to use Kotlin as language. Official documents are written here

Filename

java -> filename.java
kotlin -> filename.kt

Start Project

Make main() and Configuration

To start writing in intelliJ, I added the codes below, and for configurations, I added “Application”

class Main{
companion object {
@JvmStatic public fun main(args : Array<String>) {
//write codes here!
}
}
}

Basic

A. Package

same story as java, but you write the method as a function

package foo.bar

import foo.Bar
import foo.*

fun baz() {}

class Goo {}

// ...

/* ... */

B. Variable

All variables are treated as classes in Kotlin. So for instance, when in Java int is mergeed to Int.

// Mutable
var arg1 = 1
arg1 = 2 // possible
// Read only
val arg2 = 1
arg2 = 2 // impossible

C. Type Interface

Kotlin supports type interface. Unlike java, you don’t have to define the type, such as String or Int, because the variable will automatically define it for you.

// Type inference
val number = 1 // Int

// Define type
val text: String

D. Nullable

This is very different from Java, but can define null in a variable! But you have to write the variable in a specific way with “?”

// Non Null
val nonNull: String
nonNull = null // impossible

// Nullable
val nullable: String?
nullable = null // possible

This will be furthur discussed in Introduction to Kotlin 3

E. Array

// ["a", "b", "c"]
val array = arrayOf("a", "b", "c")

// Empty array[100]
val emptyArray: Array<String?> = arrayOfNulls(100)

// ["0", "1", "4", ...]
val ascArray = Array(100, { i -> (i * i).toString() })


// Get and Set
array[0] = "d"
println(array[0])

array.set(0, "d")
println(array.get(0))

F. Map

// Map<>
val map = mapOf(1 to "A", 2 to "B")

// MutableMap<>
val mutableMap = mutableMapOf(1 to "A", 2 to "B")

// HashMap<>
val hashMap = hashMapOf(1 to "A", 2 to "B")

// Get and Set
mutableMap[1] = "a"
println(mutableMap[1])

mutableMap.set(1, "aa")
println(mutableMap.get(1))

G. Numerical Literals

In Kotlin, you can use _(underscore) for numerals, bytes, etc.. for readability.

val oneMillion = 1_000_000
val hexBytes = 0xFF_EC_DE_5E
val bytes = 0b11010010_01101001_10010100_10010010

H. Getter/Setter

In Kotlin, Getter/Setter is made automatically. More like, you can access variables inside a class without making getter and setter functions.
var makes a Getter/Setter(Mutable), and val makes only a Getter(Read-only).

In Java,

class Data {
private int param;

Data(int param) {
this.param = param;
}

public int getParam() {
return this.param;
}

public void setParam(int param) {
this.param = param;
}
}

in Kotlin

class Data {
val param: Int

constructor(param: Int) {
this.param = param
}
}

even shorter version in Kotlin (when you don’t use a constructor.)

class Data(var param: Int)

Accessing from outside, you can just make a equal(=) to the variable.

val data = Data()
data.param = 1 // called setter
println(data.param) // called getter

I. Customizing Getter/Setter

If you want to customize getter/setter, this is the way.

var upperString: String
get() = this.toString()
set(value) {
value.toUpperCase()
}

and just use the function from outside

val isAdult get() = age >= 20 // Property type inferred to be 'Boolean'

Kotlin omits most of the get() function, and instead use Variables, so it is very very useful!

For instance, for getLayoutInflator() which gets Android Activities, that returns specific instances, also omits get() part.

But for functions like getServices(), whose internal processing is complicating, the get() is not omitted.

Java

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

final LayoutInflater inflater = getLayoutInflater();
// or

final LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}

Kotlin

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)

val inflater = layoutInflater

// or

val inflater = getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
}

J. Any

In Kotlin, all classes inherits Any Object.
It looks the same as Object class in java, but it is different and that, it is a empty class with no members.

K. Late Initialize

lateinit is late initialization. If you includelateinitin a variable, you don’t have to instantiate it in a constructor. Why? Because in many cases, you will do dependency injections and want to define the value of the variable after you instantiated it. read more in here!

public class Test {

lateinit var mock: Mock

@SetUp fun setup() {
mock = Mock()
}

@Test fun test() {
mock.do()
}
}

This is the basic! Next will be about classes, returns, modifiers and null safety.

L. by Lazy

By using this, it is possible to initialize a read-only variable when you use it. You just put by lazy after the variable.

val lazyValue: String by lazy {
println("computed!")
"Hello"
}

This is how you use it.

fun main(args: Array<String>) {
println(lazyValue)
println(" lazy value:'$lazyValue'")
}

The out put will be

computed!
Hello
lazy value: Hello!
Ayako Sayama

Written by

Front-End Developer, Graphic and UI/UX Designer

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade