When I started developing in Kotlin, I would like to write a point that I was confused about. May Java developers who read this article get off to a good start in Kotlin development ...
Let's declare a variable in Java.
int i = 0;
If you write this in Kotlin
var i: Int = 0
It will be like this.
variable name: typeSo what about var?
var (variable)
Same as Java non-final variables. It can be reassigned after initialization.
val (value)
Same as Java variable with final. It cannot be reassigned after initialization.
val i: Int = 0
i = 1 //Compile error
var i: Int = 0
i = 1 // OK
** If possible, declare variables with val of reassignment NG.
Use var only when you need it. ** **
By the way, even in the case of val, it is not necessary to initialize at the declaration point.
val i: Int
if (flag) {
i = 1
}
else {
i = 4
}
Kotlin has type inference.
If you declare a variable without using inference, it's ↓
val i: Int = 0
You can omit the type by using inference ↓
val i = 0
Let's infer the type from a literal.
val i = 0 // Int
val l = 0L // Long
val f = 0F // Float
val d = 0.0 // Double
val c = 'c' // Char
val str = "str" // String
Let's infer the return value of the function.
fun getString(): String {
return "kotlin"
}
val str = getString()
// val str:You don't have to write String
switchKotlin does not have switch. There is when instead.
Let's deal with enums that represent days of the week.
enum class DayOfWeek {
SUN, MON, TUE, WED, THU, FRI, SAT
}
val dayOfWeek: DayOfWeek = DayOfWeek.MON
//Saturdays and Sundays are good, otherwise bad
when (dayOfWeek) {
DayOfWeek.SUN -> println("Good!")
DayOfWeek.SAT -> println("Good!")
else -> println("Bad...")
}
If there are two or more expressions, you can enclose them in {``} after-> .
when {
`conditions` -> { `formula` }
}
You cannot use the break clause in when. Break by default. If you want to handle multiple conditions at once, separate them with commas.
when (dayOfWeek) {
DayOfWeek.SUN, DayOfWeek.SAT -> println("Good!")
else -> println("Bad...")
}
, whenandtry` are expressions instead of statementsSince ʻif, when, and try` are expressions, you can assign the result to a variable or treat it as the return value of a function.
val v = if (flag) {
"I like Kotlin!"
} else {
"(T_T)"
}
The last evaluated expression is the result of if.
If flag is true, "I like Kotlin!" Will result in an if expression.
Assigned to the variable v.
The above example has exactly the same usage as the Java ternary operator. There is no ternary operator in kotlin.
// Java
String v = flag ? "I like Kotlin!" : "(T_T)";
voidThere is no void in Kotlin.
Use the type ʻUnit` to represent a function with no return value.
fun doSomething(): Unit {
// doSomething
}
There are useful functions that instantiate a List or Array.
val list = listOf(0, 1, 2)
val empty = emptyList<Int>()
val arr = arrayOf('a', 'b', 'c')
val empty = emptyArray<Char>()
XXXof () is a variadic function that allows you to describe the elements of a collection.
The ʻemptyXXX ()` function is useful for generating empty collections.
| Mold | Generate | 空Generate |
|---|---|---|
| Array | arrayOf() | emptyArray() |
| List | listOf() | emptyList() |
| Set | setOf() | emptySet() |
| Map | mapOf() | emptyMap() |
If the element cannot be inferred, you need to specify a type parameter.
val numList = listOf<Number>(0.0F, 100, 1_000_000_000_000L)
There are two main types of Kotlin collections.
A mutable collection (Mutable) and an immutable collection (Immutable).
The ʻadd ()function that adds an element and theremove ()` function that removes it only exist in mutable collections.
| Immutable | Mutable |
|---|---|
| List | MutalbeList |
| Set | MutableSet |
| Map | MutableMap |
The mutableXXXof () function is useful for generating mutable collections.
val list = mutableListOf(0, 1, 2)
list.add(3)
Unlike Java, Kotlin functions and variables don't have to belong to a class.
import com.package
//Functions that do not belong to the class
fun topLevelFunction() {
// do something
}
//Variables that do not belong to the class
var topLevelVariable = 0
class Hoge {
}
Recommended Posts