[JAVA] Kotlin learning notes (features useful for development)

** Definition of main variables **

val and var

--val → Not possible with reassignment --var → reassignable

Example

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.

Example

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.


If expression that returns a value

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.

Example (This is the case with Java)

String a;
if(b) {
  a = "foo";
} else {
  a = "bar";
}

Example (Kotlin can be written like this)

val a = if(b) "foo" else "bar"

Named arguments, default arguments

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.

Example

//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

Kotlin learning notes (features useful for development)
Library collection useful for Android development
Notes for Android application development beginners
Angular framework features for web development
For JAVA learning (2018-03-16-01)
List of libraries useful for ios application development
Is Java SE8 Silver useful for Java development work? ??
[Android / Kotlin] Detailed notes 2
Notes for AST analysis
Ruby Learning # 23 For Loops
Definitely useful! Debug code for development in Ruby on Rails
[Kotlin] Resources and tips for learning a new programming language