[JAVA] Introduction to kotlin for iOS developers ⑥-Kotlin creation

Now it's time to write Kotlin. It's been a long time, but I'll do my best.

First convert Java to Kotlin

Check the procedure to convert again, including the meaning of review. Screenshot 2017-03-17 12.07.03.png First, open this MainActivity.java. Then open Code and select "Convert Java File to Kotlin File" at the bottom. スクリーンショット 2017-03-17 12.24.59.png Then, in no time スクリーンショット 2017-03-17 12.07.52.png It will be rewritten to Kotlin.

(* It's a convenient function, but it's not very reliable, so it's safer to recognize that it will be rewritten with the accuracy of automatic translation of Go ○ gle. A few lines of code is a problem. I don't think it's possible, but when there are more than a few dozen lines, various suspicious points will appear.)

import and "alt + enter"

Now, let's write it. First, connect the part on the xml file created last time and kotlin with id. (In short, let's connect to the outlet) As a way of writing

IdConnect.kt


val [name] = findViewById(R.id.[id registered in xml]) as [Part name]

is. (You don't need [] itself) So, let's write a displayTextView specifically.

MainActivity.kt


val displayTextView = findViewById(R.id.displayTextView) as TextView

If you write so far, you should see an error in the code. スクリーンショット 2017-03-17 12.08.39.png It means, "What is android.widget.TextView? Let me introduce you."

I don't think I had a lot of chances to encounter such an error when writing in Xcode. Because in the case of iOS, "import UI Kit" is almost all solved. However, in the case of android, the one used in the Activity file is imported at any time, so it is annoying that you have to import the part every time you add a new part.

So, import the TextView to fix what's angry right now. Now, take a look at the previous image. You are instructed to press "alt + enter" with the message. When I push it, スクリーンショット 2017-03-20 13.00.58.png

What an automatic import. (Well, I think it would be nice if you could import it automatically when you wrote the code if you could do that.)

It is convenient to remember that the operation "alt + enter" performed here is an operation that automatically corrects the optimum result when an error occurs.

Connection with Id (continued)

Let's continue to connect other buttons to the outlet (work like).

MainActivity.kt



        override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
            val displayTextView = findViewById(R.id.displayTextView) as TextView
    //(Add from here)
            val no0Button = findViewById(R.id.no0Button) as Button
        val no1Button = findViewById(R.id.no1Button) as Button
        val no2Button = findViewById(R.id.no2Button) as Button
        val no3Button = findViewById(R.id.no3Button) as Button
        val no4Button = findViewById(R.id.no4Button) as Button
        val no5Button = findViewById(R.id.no5Button) as Button
        val no6Button = findViewById(R.id.no6Button) as Button
        val no7Button = findViewById(R.id.no7Button) as Button
        val no8Button = findViewById(R.id.no8Button) as Button
        val no9Button = findViewById(R.id.no9Button) as Button
        val additionButton = findViewById(R.id.additionButton) as Button
        val subtractButton = findViewById(R.id.subtractButton) as Button
        val multiplicationButton = findViewById(R.id.multiplicationButton) as Button
        val divisionButton = findViewById(R.id.divisionButton) as Button
        val clearButton = findViewById(R.id.clearButton) as Button
        val resultButton = findViewById(R.id.resultButton) as Button
    //(So far)

It may seem a bit long, but I can't help but make a calculator.

Prepare variables

MainActivity.kt


        var symbol = symbolType.additon
    var a: Int = 0
    enum class symbolType {
        additon,
        subtract,
        multipication,
        division
    }

symbolType is an enum created for discriminating the four arithmetic operations, and is a variable a for storing the variable symbol and the first number to be calculated.

It's a quick flow, but it's how to write an enum.

enum.kt


    enum class [name](val[値のname]:[Valuetype]) {
        [Pattern 1](value),
        [Pattern 2](value),
        [Pattern 3](value)
    }

Function preparation

Next, we will create a function that works with buttons. How to write a function looks like this.

function.kt


fun [name]([Argument name]: [Argument type],[Second argument]: [Argument type]...):[Return type] {
[Describe the processing content]
}

So let's write it outside the {} of onCreate in MainActivity.kt. The first is a function that switches symbolType.

MainActivity.kt


        override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
       }
//(Addition from here)
   fun tapSymbolChange(text: String, symbol: symbolType): symbolType{
        a = Integer.parseInt(text)
        return symbol
    }
    

Is it like that? I think I can write it more beautifully, but at my level it's about this. Let's take a second look and next is a function that changes the display of displayTextView by pressing the number button.

MainActivity.kt


   fun tapSymbolChange(text: String, symbol: symbolType): symbolType{
        a = Integer.parseInt(text)
        return symbol
    }
        //(Addition from here)

    fun tapNumButton(text: String, num: Int) : String {

        if (text == "0") {
            return  num.toString()
        } else {
            return  text + num.toString()
        }
    }

And finally, it is a function to display the calculation result by pressing the "=" button.

MainActivity.kt


   fun tapNumButton(text: String, num: Int) : String {

        if (text == "0") {
            return  num.toString()
        } else {
            return  text + num.toString()
        }
    }
        //(Addition from here)
    fun calculation(a: Int, b: Int, symbol: symbolType): String{
        when(symbol){
            symbolType.additon -> return (a + b).toString()
            symbolType.subtract -> return (a - b).toString()
            symbolType.multipication -> return (a * b).toString()
            symbolType.division ->
                if (b != 0){
                    return (a / b).toString()
                }else {
                    return "error"
                }
        }
    }
    

I said last, that's a lie

I'm sorry, it's a light joke. You really have to set the behavior when each button is tapped at the end (the part such as addTarget in Xcode)

setOnClickListner.kt


[Part name].setOnClickListner{[Processing content]}

It's very simple to write (compared to Java).

MainActivity.kt


    no0Button.setOnClickListener {
            val text = displayTextView.text.toString()
            displayTextView.text = "0"
            displayTextView.text = tapNumButton(text = text, num = 0) }
        no1Button.setOnClickListener {
            val text = displayTextView.text.toString()
            displayTextView.text = "0"
            displayTextView.text = tapNumButton(text, 1) }
        no2Button.setOnClickListener {
            val text = displayTextView.text.toString()
            displayTextView.text = "0"
            displayTextView.text = tapNumButton(text, 2) }
        no3Button.setOnClickListener {
            val text = displayTextView.text.toString()
            displayTextView.text = "0"
            displayTextView.text = tapNumButton(text, 3) }
        no4Button.setOnClickListener {
            val text = displayTextView.text.toString()
            displayTextView.text = "0"
            displayTextView.text = tapNumButton(text, 4) }
        no5Button.setOnClickListener {
            val text = displayTextView.text.toString()
            displayTextView.text = "0"
            displayTextView.text = tapNumButton(text, 5) }
        no6Button.setOnClickListener {
            val text = displayTextView.text.toString()
            displayTextView.text = "0"
            displayTextView.text = tapNumButton(text, 6) }
        no7Button.setOnClickListener {
            val text = displayTextView.text.toString()
            displayTextView.text = "0"
            displayTextView.text = tapNumButton(text, 7) }
        no8Button.setOnClickListener {
            val text = displayTextView.text.toString()
            displayTextView.text = "0"
            displayTextView.text = tapNumButton(text, 8) }
        no9Button.setOnClickListener {
            val text = displayTextView.text.toString()
            displayTextView.text = "0"
            displayTextView.text = tapNumButton(text, 9) }
        additionButton.setOnClickListener {
            val text = displayTextView.text.toString()
            displayTextView.text = "0"
            symbol = tapSymbolChange(text, "add") }
        subtractButton.setOnClickListener {
            val text = displayTextView.text.toString()
            displayTextView.text = "0"
            symbol = tapSymbolChange(text, "sub") }
        multiplicationButton.setOnClickListener {
            val text = displayTextView.text.toString()
            displayTextView.text = "0"
            symbol = tapSymbolChange(text, "mult") }
        divisionButton.setOnClickListener {
            val text = displayTextView.text.toString()
            displayTextView.text = "0"
            symbol = tapSymbolChange(text, "div") }
        clearButton.setOnClickListener { displayTextView.text = "0" }
        resultButton.setOnClickListener {
            val b = Integer.parseInt(displayTextView.text.toString())
            displayTextView.text = calculation(a, b = b, symbol = symbol) }


It's very simple. If this is Java ... (Omitted below

It's cute kotlin

That's it. Let's run it on the emulator. I hope this will increase the number of iOS developers who can reach out to kotlin.

As a bonus

Let's expose the whole of MainActivity.kt because it's a big deal.

MainActivity.kt



import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.TextView

class MainActivity : AppCompatActivity() {

    var symbol = symbolType.additon
    var a: Int = 0


    enum class symbolType {
        additon,
        subtract,
        multipication,
        division
    }


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

        val displayTextView = findViewById(R.id.displayTextView) as TextView
        val no0Button = findViewById(R.id.no0Button) as Button
        val no1Button = findViewById(R.id.no1Button) as Button
        val no2Button = findViewById(R.id.no2Button) as Button
        val no3Button = findViewById(R.id.no3Button) as Button
        val no4Button = findViewById(R.id.no4Button) as Button
        val no5Button = findViewById(R.id.no5Button) as Button
        val no6Button = findViewById(R.id.no6Button) as Button
        val no7Button = findViewById(R.id.no7Button) as Button
        val no8Button = findViewById(R.id.no8Button) as Button
        val no9Button = findViewById(R.id.no9Button) as Button
        val additionButton = findViewById(R.id.additionButton) as Button
        val subtractButton = findViewById(R.id.subtractButton) as Button
        val multiplicationButton = findViewById(R.id.multiplicationButton) as Button
        val divisionButton = findViewById(R.id.divisionButton) as Button
        val clearButton = findViewById(R.id.clearButton) as Button
        val resultButton = findViewById(R.id.resultButton) as Button





        no0Button.setOnClickListener {
            val text = displayTextView.text.toString()
            displayTextView.text = "0"
            displayTextView.text = tapNumButton(text = text, num = 0) }
        no1Button.setOnClickListener {
            val text = displayTextView.text.toString()
            displayTextView.text = "0"
            displayTextView.text = tapNumButton(text, 1) }
        no2Button.setOnClickListener {
            val text = displayTextView.text.toString()
            displayTextView.text = "0"
            displayTextView.text = tapNumButton(text, 2) }
        no3Button.setOnClickListener {
            val text = displayTextView.text.toString()
            displayTextView.text = "0"
            displayTextView.text = tapNumButton(text, 3) }
        no4Button.setOnClickListener {
            val text = displayTextView.text.toString()
            displayTextView.text = "0"
            displayTextView.text = tapNumButton(text, 4) }
        no5Button.setOnClickListener {
            val text = displayTextView.text.toString()
            displayTextView.text = "0"
            displayTextView.text = tapNumButton(text, 5) }
        no6Button.setOnClickListener {
            val text = displayTextView.text.toString()
            displayTextView.text = "0"
            displayTextView.text = tapNumButton(text, 6) }
        no7Button.setOnClickListener {
            val text = displayTextView.text.toString()
            displayTextView.text = "0"
            displayTextView.text = tapNumButton(text, 7) }
        no8Button.setOnClickListener {
            val text = displayTextView.text.toString()
            displayTextView.text = "0"
            displayTextView.text = tapNumButton(text, 8) }
        no9Button.setOnClickListener {
            val text = displayTextView.text.toString()
            displayTextView.text = "0"
            displayTextView.text = tapNumButton(text, 9) }
        additionButton.setOnClickListener {
            val text = displayTextView.text.toString()
            displayTextView.text = "0"
            symbol = tapSymbolChange(text, symbolType.additon) }
        subtractButton.setOnClickListener {
            val text = displayTextView.text.toString()
            displayTextView.text = "0"
            symbol = tapSymbolChange(text, symbolType.subtract) }
        multiplicationButton.setOnClickListener {
            val text = displayTextView.text.toString()
            displayTextView.text = "0"
            symbol = tapSymbolChange(text, symbolType.multipication) }
        divisionButton.setOnClickListener {
            val text = displayTextView.text.toString()
            displayTextView.text = "0"
            symbol = tapSymbolChange(text, symbolType.division) }
        clearButton.setOnClickListener { displayTextView.text = "0" }
        resultButton.setOnClickListener {
            val b = Integer.parseInt(displayTextView.text.toString())
            displayTextView.text = calculation(a, b = b, symbol = symbol) }

    }


    fun tapSymbolChange(text: String, symbol: symbolType): symbolType{
        a = Integer.parseInt(text)
        return symbol
    }
    fun tapNumButton(text: String, num: Int) : String {

        if (text == "0") {
            return  num.toString()
        } else {
            return  text + num.toString()
        }
    }

    fun calculation(a: Int, b: Int, symbol: symbolType): String{
        when(symbol){
            symbolType.additon -> return (a + b).toString()
            symbolType.subtract -> return (a - b).toString()
            symbolType.multipication -> return (a * b).toString()
            symbolType.division ->
                if (b != 0){
                    return (a / b).toString()
                }else {
                    return "error"
                }
        }
    }
}

Please also include other articles

Introduction to kotlin for iOS developers ①-Environment construction Introduction to kotlin for iOS developers (2) -Project creation Introduction to kotlin for iOS developers ③-About gradle Introduction to kotlin for iOS developers ④-Type [Introduction to kotlin for iOS developers ⑤-Practical XML] (http://qiita.com/parappa1002/items/867c5b30055312e74fdb) Introduction to kotlin for iOS developers ⑥-Kotlin creation

Recommended Posts

Introduction to kotlin for iOS developers ⑥-Kotlin creation
Introduction to kotlin for iOS developers ②-Project creation
Introduction to kotlin for iOS developers ④-Type
Introduction to kotlin for iOS developers ⑤-Practical XML
Introduction to kotlin for iOS developers ③-About gradle
Introduction to kotlin for iOS developers ①-Environment construction
Kotlin Class to send to Java developers
Introduction to Programming for College Students: Introduction
Generics of Kotlin for Java developers
Kotlin Class part.2 to send to Java developers
Introduction to java for the first time # 2
Introduction to Programming for College Students: Variables
Kotlin scope functions to send to Java developers
Interoperability tips with Kotlin for Java developers
Needed for iOS 14? How to set NSUserTrackingUsageDescription
Memo for migration from java to kotlin
Introduction to Ruby 2
Kotlin functions and lambdas to send to Java developers
Introduction to Ratpack (Extra Edition) --Ratpack written in Kotlin
Introduction to SWING
Introduction to web3j
Introduction to Micronaut 1 ~ Introduction ~
Getting started with Kotlin to send to Java developers
[Java] Introduction to Java
Introduction to migration
Introduction to java
Introduction to Doma
An introduction to Groovy for tedious Java engineers
[Introduction to Java] Basics of java arithmetic (for beginners)
From the introduction of devise to the creation of the users table
Introduction to programming for college students (updated from time to time)
[Practice! ] Introduction of JFrame (explaining up to screen creation)
Introduction to Java for beginners Basic knowledge of Java language ①
Introduction to Programming for College Students: Making a Canvas
How to study kotlin for the first time ~ Part 2 ~
How to study kotlin for the first time ~ Part 1 ~
Introduction to JAR files
Introduction to Ratpack (8)-Session
Introduction to RSpec 1. Test, RSpec
Introduction to bit operation
Introduction to Ratpack (6) --Promise
Introduction to Ratpack (9) --Thymeleaf
Introduction to PlayFramework 2.7 ① Overview
Introduction to Android Layout
Road to REPL (?) Creation (3)
Introduction to design patterns (introduction)
Introduction to Practical Programming
Introduction to javadoc command
Introduction to jar command
Introduction to Ratpack (2)-Architecture
Introduction to lambda expression
Introduction to java command
19 Corresponds to object creation
Road to REPL (?) Creation (1)
Introduction to RSpec 2. RSpec setup
Introduction to Keycloak development
Introduction to javac command
Road to REPL (?) Creation (2)
An introduction to functional programming for object-oriented programmers in Elm
Introduction to Programming for College Students: Preparation Let's Install Processing
Introduction to batch files (for statements, arrays, deferred environment variables)