Getting started with Kotlin to send to Java developers

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

Variable declaration

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.

So what about var?

var and val

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
    }

Type inference

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

There is no switch

Kotlin 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...")
    }

ʻIf, whenandtry` are expressions instead of statements

Since ʻ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)";

There is no void

There is no void in Kotlin. Use the type ʻUnit` to represent a function with no return value.

fun doSomething(): Unit {
  // doSomething
}

collection

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)

Mutable collection

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)

Functions and variables do not have to belong to a class

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

Getting started with Kotlin to send to Java developers
Kotlin Class to send to Java developers
Kotlin Class part.2 to send to Java developers
Kotlin scope functions to send to Java developers
Kotlin functions and lambdas to send to Java developers
Getting Started with Java Basics
Getting started with Java lambda expressions
Getting Started with Ruby for Java Engineers
Getting Started with Java Starting from 0 Part 1
Interoperability tips with Kotlin for Java developers
Kotlin's Null safety to send to Java developers
Returning to the beginning, getting started with Java ② Control statements, loop statements
Links & memos for getting started with Java (for myself)
Getting Started with DBUnit
Getting Started with Swift
Getting Started with Docker
Getting Started with Doma-Introduction to the Criteria API
Getting Started with Doma-Transactions
Getting started with Java programs using Visual Studio Code
I want to transition screens with kotlin and java!
Getting Started with Legacy Java Engineers (Stream + Lambda Expression)
Getting Started with Doma-Annotation Processing
Java to play with Function
Connect to DB with Java
Connect to MySQL 8 with Java
Getting Started with JSP & Servlet
Getting Started with Spring Boot
Getting Started with Ruby Modules
Going back to the beginning and getting started with Java ① Data types and access modifiers
Getting started with Java and creating an AsciiDoc editor with JavaFX
How to use trained model of tensorflow2.0 with Kotlin / Java
First year Java developers on udemy get started with PHP
I want to make a list with kotlin and java!
I want to make a function with kotlin and java!
I want to implement various functions with kotlin and java!
Memo: Kotlin + Room + RecyclerView + DataBinding (Part 2)
Kotlin Class part.2 to send to Java developers
Java to learn with ramen [Part 1]
Getting Started with Java_Chapter 5_Practice Exercises 5_4
[Java] Points to note with Arrays.asList ()
Dare to challenge Kaggle with Java (1)
I tried to interact with Java
[Google Cloud] Getting Started with Docker
Getting Started with Docker with VS Code
Generics of Kotlin for Java developers
Java, arrays to start with beginners
CompletableFuture Getting Started 2 (Try to make CompletableFuture)
[Android] Convert Android Java code to Kotlin
I want to return to the previous screen with kotlin and java!
What I thought about when I started migrating from Java to Kotlin
Getting Started with Doma-Criteria API Cheat Sheet
[Java] How to compare with equals method
Convert all Android apps (Java) to Kotlin
[Note] How to get started with Rspec
Getting Started with Docker for Mac (Installation)
Introduction to algorithms with java --Search (depth-first search)
Getting Started with Parameterization Testing in JUnit
Getting Started with Ratpack (4)-Routing & Static Content
Introduction to kotlin for iOS developers ⑥-Kotlin creation
Getting started with the JVM's GC mechanism
Java: How to send values from Servlet to Servlet
[Kotlin] Delete files with duplicate contents [Java]