startalks

スマホアプリ(Android/iOS)、IoT、AI、データサイエンス

【Kotlin】2回目 言語基礎(基本文法)

目次
①定義
②特徴
③基本文法
④参考

①定義

Kotlin(コトリン)は、ジェットブレインズ社が開発した、静的型付けのオブジェクト指向プログラミング言語

②特徴

 ・簡潔
  POJOクラスを一行で書いちゃう。
  例)

  data class Customer(val name: String, val email: String, val company: String)

 ・Null安全
  NullPointerExceptionを排除すべく、変数にタイプアノテーションを付けるか、初期化する必要がある。
  例)

  var output: String
  output = null   // Compilation error:This variable must either have a type annotation or be initialized

 ・操作可換性ある
  JavaまたはJavaScriptで書いたコードを実行可能。
  例)Java

  import io.reactivex.Flowable
  import io.reactivex.schedulers.Schedulers
  
  Flowable
      .fromCallable {
          Thread.sleep(1000) //  imitate expensive computation
          "Done"
      }
      .subscribeOn(Schedulers.io())
      .observeOn(Schedulers.single())
      .subscribe(::println, Throwable::printStackTrace)

  例)JavaScript

  import kotlin.browser.window
  
  fun onLoad() {
      window.document.body!!.innerHTML += "<br/>Hello, Kotlin!"
  }

③基本文法

・パッケージ

 package my.demo
 import java.util.*

・関数

 //Int型パラメータ、Int型戻り値
 fun sum(a: Int, b: Int): Int {
    return a + b
 }
 //Unit型戻り値(voidと同じ)。省略してもOK。
 fun sum(a: Int, b: Int): Unit {
    println("sum of $a and $b is ${a + b}")
 }

・変数

 read-onlyのローカル変数。

 val a: Int = 1  // immediate assignment
 val b = 2   // `Int` type is inferred
 val c: Int  // Type required when no initializer is provided
 c = 3       // deferred assignment

 ミュータブルな変数。

 var x = 5 // `Int` type is inferred
 x += 1

・コメント(Javaと一緒)

・String templates

 var a = 1
 // simple name in template:
 val s1 = "a is $a" 

 a = 2
 // arbitrary expression in template:
 val s2 = "${s1.replace("is", "was")}, but now is $a"

・条件式

・ループ(Javaと一緒)

・レンジ

 val x = 10
 val y = 9
 if (x in 1..y+1) {
     println("fits in range")
 }

・コレクション(Javaと一緒)

・クラス

 val rectangle = Rectangle(5.0, 2.0) //'new'キーワードは不要
 val triangle = Triangle(3.0, 4.0, 5.0)

④参考

・コーディング規約
Coding Conventions - Kotlin Programming Language

まとめ
次回はデータ型について見ていきます~