About Kotlin

SLP KBIT Advent Calendar 2017 12/17 (Sun) article.

Introduction

Hi, I'm Nya-chan (itakumi), a 3rd year undergraduate student at the Institute of Student Programming, Kagawa University. Since the Kotlin boom has come to me recently, I would like to write about what Kotlin tastes like in comparison with Java, which everyone will be familiar with so that even first and second graders will be interested. This is the one and only Kotlin calendar. Occasionally, please be healed by seeing just a language introduction article that is not high level at all.

First of all, about Kotlin

First of all, I think there are some people who say Kotlin before talking about the concrete syntax. Kotlin is a statically typed object-oriented language developed by JetBrains' Andrey Breslav and Dmitry Gemerov. The logo is the one below

image.png

JetBrains is famous for developing programming language development environments such as IntelliJ IDEA and RubyMine. Kotlin is an improved version of the Java language based on JetBrains' experience that makes it even simpler and more secure. So Kotlin is a so-called JVM language that runs on a Java virtual machine (JVM). Scala written by Mr. Gray Bear yesterday is also a JVM language. Well, that's all for the first explanation, and I'd like to look at the specific syntax from now on.

About syntax

Hello World What is the first program you make when you first touch the program language? ?? ?? ?? so! !! ** Hello World ** That's right. The top is the Java Hello World program and the bottom is Kotlin.

HelloWorld.java


public class Hello {
  public static void main(String[] args) {
    System.out.println("Hello, world!");
  }
}

HelloWorld.kt


fun main(args: Array<String>) {
    println("Hello, world!")
}

What? Very short !!! Yes Kotlin is very short. Java is long. Kotlin is much cleaner to write than Java. You don't need a semicolon at the end of the sentence. Did the JetBrains people forget about the semicolon? ?? You can also define how to write a class by using the fun function name (variable name: type name). System.out.println is also OK with just println !!

How to handle variables

Next are variables. Basically, the syntax is like this.

val num = 10    //Cannot be changed with val
var i = 10      //Can be changed with var
i = 20

Also, if you want to specify the type explicitly,

val str: String = "Enthusiasm"    // 失礼しましたEnthusiasmと出てしまいました

To do. At first, val and var may be confused, but once you get used to it, there is no problem.

Well, you can write the basic syntax in a straightforward manner, but it will be long, so if you are interested in other things, please check it out.

Nullable Then the syntax is simpler and easier to understand than Java, but that's it? So I'll show you what's in Kotlin though it doesn't have Java. There is a NullPointerException that people who are developing something in Java will definitely come across. It is a guy who is often referred to as Nurponurupo. Kotlin has a movement to eradicate the NullPointerException (a lie). Kotlin can only assign null with a special type called Nullable. This will prevent NullPointerException. The specific writing method is as follows.

//Ordinary String type cannot be assigned null
var str1: String = "Banana"
str1 = null    //Compile error
val len1 = str1.length    //This is ok. str1 can never be assigned null, so it will not be a nullpo

//I tried to make it Nullable
var str2: String? = "Basilisk time"
str2 = null    //No compilation error
val len2 = str2.length    //Compile error!!Become a nullpo--Is said

//You can also write like this
val len2 = str2?.length    //This will run if it's not null, otherwise it will return null
val len2 = b?.length ?: -1    //Conditional branching by null can be easily done with the Elvis operator.

I said that Kotlin can prevent nullpo by using this, but I think that there are few systems currently running on Kotlin alone. It's almost like using Kotlin to add functionality to the original Java system. So even though it's written in Kotlin, nullpo happens when Java is involved. I would like to note that writing in Kotlin does not mean that there is no nullpo.

Let's make something

Expose the code of the Android stopwatch app you made earlier. It's a fucking code that doesn't think about object orientation at all. A detailed explanation will be given somewhere in the future. .. ..


class MainActivity : AppCompatActivity() {

    val handler = Handler()
    var timeValue = 0


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val timeText = findViewById<TextView>(R.id.timeText)
        val startButton = findViewById<Button>(R.id.start)
        val stopButton = findViewById<Button>(R.id.stop)
        val resetButton = findViewById<Button>(R.id.reset)

        val runnable = object : Runnable {
            override fun run() {
                timeValue++

                timeToText(timeValue)?.let {
                    timeText.text = it
                }
                handler.postDelayed(this, 1000)
            }
        }

        startButton.setOnClickListener {
            handler.post(runnable)
        }

        stopButton.setOnClickListener {
            handler.removeCallbacks(runnable)
        }

        resetButton.setOnClickListener {
            handler.removeCallbacks(runnable)
            timeValue = 0
            timeToText()?.let {
                timeText.text = it
            }
        }
    }


    private fun timeToText(time: Int = 0): String? {
        return if (time < 0) {
            null
        } else if (time == 0) {
            "00:00:00"
        } else {
            val h = time / 3600
            val m = time % 3600 / 60
            val s = time % 60
            "%1$02d:%2$02d:%3$02d".format(h, m, s)
        }
    }
}

Wow it worked! !! !!

スクリーンショット 2017-12-15 11.16.09.png

Summary

I wrote an article about Kotlin this time, but I still need to learn. After a lot of research, I found a lot of things I didn't know. Let's study together with interested people! !! Also, I'm looking forward to the Aqours fan meeting! !! I'm going to Fukuoka and Makuhari! !! Three └ (┐ 卍 ^ o ^) 卍 Durururu

Digression

We're happy to see the addition of ** "Include Kotlin support" ** to the newest Android Studio. The first preparation will be much easier.

Recommended Posts

About Kotlin
About =
What I learned about Kotlin
About method.invoke
About attr_accessor
About Hinemos
About inheritance
About params
About Docker
About Rails 6
About form_for
About Spring ③
Kotlin Bytecode
About enum
Kotlin infix
About polymorphism
About Optional
About hashes
About JitPack
About Dockerfile
About this ()
About devise
About encapsulation
About Docker
About JAVA_HOME
About active_hash
About static
About exceptions
About scope
[Maven] About Maven
About Spring Dependency Injection using Java, Kotlin
About exception handling
About Java interface
[Java] About Java 12 features
About Rails routing
HMAC in Kotlin
About cyclomatic complexity
About exception handling
About AsyncTask Generics
About Ruby symbols
About array multiplication
[Java] About arrays
About HotSpot VM
About ruby ​​form
[Swift] About generics
About Active Storage
About class inheritance.
About Spring AOP
About Ruby Hashes
About singular methods
About getter setter
About build tools
About MacinCloud introduction
[Note] About nil
About keyword arguments
Chew about API
[About double hash]
About installing Cocoapods
Something about java
Where about java
About HttpServlet () methods