--val → Not possible with reassignment --var → reassignable
val a: String = "foo"
a = "bar" //Get an error
var b: String = "foo"
b = "bar" //No error
** It seems better to use val as much as possible and only when necessary **
nullable
Variables ** that can be assigned null ** and variables ** that cannot ** are distinguished as different types. For example, if it is a String type, unless you declare it as a String? Type with a? At the end. You cannot assign null.
val a: String = null //Get an error
val b: String? = null //No error
In this way, unintended null assignment will result in a compile-time error. It has the effect of preventing slimy.
Because Kotlin's if can be used not only as an if statement but also as an if expression You can return a value. For this reason, it is convenient because there are many situations where you can write concisely.
String a;
if(b) {
a = "foo";
} else {
a = "bar";
}
val a = if(b) "foo" else "bar"
Kotlin allows you to name arguments and give them default values, so Overload (overloading, defining multiple methods with the same name with different arguments and return values) You don't have to use.
//Set the default value for middleName
fun fullName(firstName: String, middleName: String = "", lastName: String)
//Only necessary arguments can be specified and passed
val name = fullName(firstName = "Jun", lastName = "Ikeda")
Recommended Posts