What I learned about Kotlin

What I learned about Kotlin

What is kotlin

Kotlin is an object-oriented programming language developed by JetBrains, famous for IntelliJ IDEA. Because the compiled code runs on the JVM, It is now possible to divert the assets created in JAVA so far.

Kotlin basic syntax

Variable declaration

//Declaring with val prevents reassignment of values
val firstName: String = "Tanaka"  
//No need to define each type in type inference
val lastName = "Taro"  
  
//Can be reassigned by declaring it with var
var age = 20  
age = 21

Array

//Array(array)Create
val nameList: Array<String> = arrayOf("tanaka", "saitou", "kimura")  
println(nameList[0]) //output by tanaka
  
//Rewriting elements of an array
nameList[1] = "sakurai"  
println(nameList[1]) //output by sakurai
  
//Array(list)Create
val animalList: List<String> = listOf("dog", "cat", "rabbit")  
println(animalList[0]) //dog outputs
  
//Rewriting elements of an array
animalList[1] = "tiger" //Error interface List is read-only

Even with List, mutableListOf () can be used to create a list that can be changed, so I'm not sure how to use Array and List properly.

map

//Map creation
val numberMap: MutableMap<String, Int> = mutableMapOf("one" to 1)  
println(numberMap["one"]) //1 is output
////Add value
numberMap["tow"] = 2  
println(numberMap)        // {one=1, tow=2}Outputs
  
//Map with mapOf
val reNumberMap: Map<Int, String> = mapOf(1 to "one")  
println(reNumberMap[1])   //1 is output
////Add value
reNumberMap["tow"] = 2    //Error mapOf is read-only

Conditional branch

//Ordinary if statement
if (true) {  
    println("if")   //if outputs
} else {  
    println("else")  
}  
  
//Kotlin doesn't have a ternary operator, so it looks like that
val animal = "dog"  
val isDog = if (animal == "dog") true else false  
println(isDog)      //true is output
  
//For empty check
val person:String? = null  
val personName = person?: "NoName"  
println(personName) //NoName is output
  
//When statement Similar to switch statement
val result = when("hoge") {  
    "hoge" -> "hoge"  
    "fuga" -> "fuga"  
     else -> "else"  
}  
println(result)     //hoge outputs

Loop processing

//while statement
var count = 5  
while(0 < count--) {  
    println("while count: ${count}")  
}  
  
//for statement
for (i in 1..5) {  
    println("for count: ${i}")  
}

Comparison of writing between JAVA and Kotlin

Add age, name, and gender to the user class I wrote the code to execute the self-introduction method.

Kotlin

user.kt

fun main() {  
    val user = userData(20, "Taro", "Men")  
    user.selfIntroduction()  
}

userData.kt

data class userData (  
    var age: Int? = 0,  
    var name: String = "NoName",  
    var gender: String? = null  
) {  
    fun selfIntroduction() {  
        println("My name is ${name}")  
        println("Age is ${age}")  
        println("Gender is ${gender}")  
    }  
}

JAVA

user.java

public class user {  
    public static void main(String[] args) {  
        userData user = new userData(20, "Taro", "Men");  
        user.selfIntroduction();  
    }  
}

userData.java

public class userData {  
    private int age;  
    private String name;  
    private String gender;  
  
    public userData(int age, String name, String gender) {  
        this.age = age;  
        this.name = name;  
        this.gender = gender;  
    }  
  
    public void selfIntroduction() {  
        System.out.println("My name is " + this.name);  
        System.out.println("Age is " + this.age);  
        System.out.println("Gender is " + this.gender);  
    }  
}

The difference I felt after writing

Hello World with Spring Boot

environment

Windows10 Pro IntelliJ Community Edition 2020.2 JAVA 14

Make a template for the project

Use Spring Initializr to get the template of the project.

The setting is Project : Gradle Project Language : Kotlin Spring Boot : 2.3.4 ** Project Metadata **: Leave default Packaging Jar Java : 14 Dependencies : Spring Web

chrome_8cN8PNZDsH.png

Finally, press ** GENERATE ** to download the project template

Build the template of the created project

From IntelliJ ** File → Open ... → Select the template of the downloaded project → Extract with the procedure of OK **

Create controller

For the demo / src / main / kotlin / com.example.demo / controller folder ** Right click → New → Press Kotlin File / Class ** Create HelloController.kt.

HelloController.kt

package com.example.demo.controller

import org.springframework.web.bind.annotation.RestController
import org.springframework.web.bind.annotation.RequestMapping

@RestController
public class HelloController {
    @RequestMapping("/")
    fun hello():String {
        return "Hello World"
    }
}

Start the web server

idea64_VFRC5iORoS.png

Click the ** play button ** on the upper right to build

Connect

Connect to http: // localhost: 8080 when the build is finished

chrome_Dk8vUW6lcC.png

Impressions

I haven't touched JAVA so much, so I was worried that Kotlin would be okay without knowing JAVA. When I suddenly started writing from Kotlin, there was no problem with Kotlin suddenly Rather, I found it easier to get started with Kotlin. When I compared it with JAVA, the amount of code in Kotlin became smaller, I felt that type inference, data classes, etc. helped keep the code simple.

Recommended Posts

What I learned about Kotlin
What i learned
What I learned ② ~ Mock ~
What I learned ① ~ DJUnit ~
Summary of what I learned about Spring Boot
What I researched about Java 8
What I researched about Java 6
What you learned about hashes
What I researched about Java 9
What you learned about symbols
What I researched about Java 7
What I researched about Java 5
About Kotlin
I will write what I learned about docker anyway (second)
I will write what I learned about docker anyway (first)
What I learned from studying Rails
What I learned with Java Gold
What I learned with Java Silver
What I researched about Java learning
Take what you've learned about Java reflection
What I learned from Java monetary calculation
What I thought about when I started migrating from Java to Kotlin
[Personal memo] I learned a little about modifiers
[Rails] I learned about database data type types!
What I learned in Java (Part 2) What are variables?
What I did when I converted java to Kotlin
Summary of what I learned in Spring Batch
[Rails] I learned about the difference between resources and resources
What I learned in Java (Part 3) Instruction execution statement
What I learned when building a server in Java
[Rilas] What I learned in implementing the pagination function.
I learned about the existence of a gemspec file
I knew what reflection was
What I learned in Java (Part 4) Conditional branching and repetition
[Swift] I thought about compare
I read the Kotlin startbook
10 Things I Hate About Android
[Android / Java] Learned about DataBinding
What I have learned in Java (Part 1) Java development flow and overview
About what I did when creating a .clj file in Clojure
[Note] What I learned in half a year from inexperienced (Java)
[Note] What I learned in half a year from inexperienced (Java) (1)
What I learned from doing Java work with Visual Studio Code
About the language to be learned
[Rails] I learned about migration files! (Adding a column to the table)
[Rails] What I learned from a little stumbling block when using ancestry