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.
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" |
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
if(true)
println("Hello")
if(false){
println("Hello")
} else if(true) {
println("Kotlin")
} else {
println("World!")
}
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
}
when (a) {
1 -> println("a == 1")
2,3 -> println("a == 2 or a == 3")
else -> {
println("otherwise")
}
}
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")
}
for (a in 1..10) println(a)
for (a in 'Z' downTo 'A') print(a)
collection
val array = arrayOf(297456, 119243,9,30)
for (a in array) {
println(a)
}
If you want to use an index
val array = arrayOf(297456, 119243,9,30)
for (i in array.indices) {
println(array[i])
}
Same as Java.
var x = 10
while (x > 0) {
println(x--)
}
do-while
do{
println("i = " + i--)
}while(i > 4)
Run Online (https://try.kotlinlang.org/#/UserProjects/6v4vmotcoemh93ckflpilmpct3/pdsmvtodipq00qvmhk75rbb9me)
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()
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 |
Same as Java
a && b (and) a || b (or) !a (not)
val multiline = """
for (c in "foo"){
print(c)
}
"""
val withTrim = """
|for (c in "foo"){
| print(c)
|}
""".trimMargin()
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()
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 |
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 |
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 functions are defined with the keyword fun
fun times(a: Int, b: Int): Int {
return a * b
}
Function execution
val result = times(2,5)
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!")
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"
}
}
equals, hashCode, toString, copy are automatically generated by defining as data class.
data class Dog(val name: String)
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"
}
})
{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}
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