[JAVA] Kotlin cheat sheet

At first

Kotlin is convenient! But now I have to use Java as well. How do you do that in Kotlin? So I made a cheat sheet. Comes with code that can be executed immediately.

What is Kotlin?

Kotlin is a new language on the Java platform, a statically typed language that is compatible with Java. A language aimed at "practicalism, conciseness, and safety", which is simpler than Java and a practical language that prevents mistakes that are common in Java. Because of its interoperability with Java, Java programs can be easily used from Kotlin. The low learning cost is also attractive for Java experienced people.

Kotlin data type

type Bit width type Example
Double 64 Floating point 12345.6
Float 32 Floating point 12345.6f
Long 64 integer 123456L 999_99_9999L 0xFF_EC_DE_5E
Int 32 integer 123456 0xFF_FF
Short 16 integer 32767 0x0F
Byte 8 integer 127 0b1010
String - String "Hello, world!\n"

Kotlin variables and constants

Variable var

var a: Float
a = 12345.6f

Constant val

val a: Int = 10000
val b = 10_000L //Separated by underscore to make digits easier to see

Declaration and initialization do not have to be simultaneous.

val c: Double
c = 12345.6

Kotlin control syntax

If expression

if(true)
    println("Hello")

Run Online

if(false){
    println("Hello")
} else if(true) {
    println("Kotlin")
} else {
    println("World!")
}

Run online

Since it is an expression, the result can be assigned. The last evaluated formula is returned.

val max = if (a > b) {
    print("a is greater than b")
    a
} else {
    print("a is less than b")
    b
}

Run online

When expression

when (a) {
    1    -> println("a == 1")
    2,3  -> println("a == 2 or a == 3")
    else -> {
        println("otherwise")
    }
}

Run online

Specify the range with in.

when (a) {
    in 1..10   -> println("a is in the range")
    !in 10..20 -> println("a is outside the range")
    else       -> println("otherwise")
}

Run online

For loop

for (a in 1..10) println(a)

Run online

for (a in 'Z' downTo 'A') print(a)

Run online

collection

val array = arrayOf(297456, 119243,9,30)
for (a in array) {
    println(a)
}

Run online

If you want to use an index

val array = arrayOf(297456, 119243,9,30)
for (i in array.indices) {
    println(array[i])
}

Run online

While loop

Same as Java.

var x = 10
while (x > 0) {
    println(x--)
}

Run online

do-while

do{
  println("i = " + i--)
}while(i > 4)

Run Online (https://try.kotlinlang.org/#/UserProjects/6v4vmotcoemh93ckflpilmpct3/pdsmvtodipq00qvmhk75rbb9me)

Kotlin data conversion

String to number

val intVal: Int = str.toInt()
val intValOrNull: Int? = str.toIntOrNull()
val doubleVal = str.toDouble()

From each type to a string

val intStr = num.toString()

Cast of numbers (eg Int to Long conversion)

val long= int.toLong()

Run online

Date processing

Date processing

Kotlin arithmetic operator

Same as Java

Example of use meaning Example of use meaning
x + y Addition x - y Subtraction
x * y Multiply x / y division
x % y Surplus
++x / x++ Increment --y / y-- Decrement

Kotlin Boolean operator

Same as Java

a && b (and) a || b (or) !a (not)

Kotlin string

    val multiline = """
    for (c in "foo"){
        print(c)
    }
    """
    val withTrim = """
    |for (c in "foo"){
    |    print(c)
    |}
    """.trimMargin()

Kotlin string template

val str = "Hello Kotlin!"
val templete = " $str is ${str.length} characters."
// >Hello Kotlin! is 13 characters.

When you want to output $ as it is

val price = 200
val multiline = """
|This is ${'$'}$price.
""".trimMargin()

Run Online

Kotlin comparison operator

Almost the same as Java, but "==" is equivalent to Java equals. Object comparison is "===" in Kotlin.

Example of use meaning Example of use meaning
x < y x is small x <= y x is small or the same
x > y x is large x >= y x is greater or the same
x == y the same x != y different
x === y Same object x !== y Objects are different

Kotlin string function

Example meaning
s.length s length
s.count() s length
s[i] i-th character
s.substring(start..end) Substring from start to end
s.substring(start,end) start to end-Substring up to 1
s.toUpperCase() Uppercase conversion
s.toLowerCase() Lowercase conversion
s.indexOf('x') 'x'Index where
s.replace(old,new) String replacement
s.replaceFirst(old,new) Replacement of the first string found
s.split(regex) To divide
s.trim() Remove front and rear white space
s.startsWith(prefix) Returns true if the string starts with frefix
s.endsWith(suffix) Returns true if the string ends with a suffix

Run Online

Kotlin collection

List

Read-only List

val items = listOf(1, 2, 3)
println(items)

Modifiable List

val numbers: MutableList<Int> = mutableListOf(1, 2, 3)
numbers.add(4)

Set

Read-only Set

var strings: Set<String> = setOf("A","B","C")

Changeable Set

var stringSet: MutableSet<String> = mutableSetOf("x","y","z")
stringSet.add("a") 
stringSet.filter { it != "x"}

Map

Read-only Map

val fruits = mapOf("apple" to 1, "orange" to 2, "banana" to 3)

Changeable Map

val readWriteMap = mutableMapOf("apple" to 1, "orange" to 2, "banana" to 3)
readWriteMap.put("melon",4)

Kotlin function

Kotlin functions are defined with the keyword fun

fun times(a: Int, b: Int): Int {
    return a * b
}

Function execution

val result = times(2,5)

Run Online

If the function body consists of one expression, you can omit the curly braces and write the expression after =. The return value can be omitted by inference.

fun times(a: Int, b: Int) = a * b

Default value can be specified for the argument. You can specify the name of the argument when calling the function.

val result = makeString(base = "world ", concl = "of Kotlin!")

Run online

Kotlin class

open class Parent{
    open fun show() = println("This is Parent")
}
class Child:Parent(){
    override fun show() = println("This is Child")
}

Initializer: Initialization code uses init block

class Person(val name: String, val isMan:Boolean, var favorite:String ){
    init {
        val s = if(isMan) "He" else "She"
        favorite =  "$s liles $favorite"
    }
}

Run online

Kotlin data class

equals, hashCode, toString, copy are automatically generated by defining as data class.

data class Dog(val name: String)

Object expression

A function that corresponds to an anonymous class in Java. object: Inheritance Class (Interface) name {implementation}

view.setOnClickListener(object: View.OnClickListener {
override fun onClick(v: View?) {
        view.text = "clicked"
    }
})

Kotlin lambda expression

{variable:Mold->processing}

Lambda expressions can be stored in variables

val minus = {x: Int, y: Int -> x - y }

If the lambda expression has one argument, you can omit the argument and use the implicit argument it

val double:(Int)->Int = {it * 2}

Interoperability with Java

Use ClassName :: class.java or instance :: class.java to get java.lang.Class

val clazz = Activity::class.java
val clazzz = this::class.java

Recommended Posts

Kotlin cheat sheet
JMeter cheat sheet
[Docker cheat sheet]
Mockito + PowerMock cheat sheet
Eclipse Collections cheat sheet
Rails Tutorial cheat sheet
SCSS notation cheat sheet
Oreshiki docker-compose cheat sheet
Docker command cheat sheet
[Eclipse] Shortcut key cheat sheet
C # cheat sheet for Java engineers
javac, jar, java command cheat sheet
Getting Started with Doma-Criteria API Cheat Sheet
About Kotlin
Technology for reading source code (cheat sheet)
[Java] Data type / string class cheat sheet
Kotlin Bytecode
Kotlin infix
Note: Cheat sheet when creating Rails Vue app