0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Kotlin公式サイトBasic syntaxの日本語メモ

Last updated at Posted at 2023-06-26

Introduction

Kotlinの理解を深めるため,以下のサイトで学習した際のメモをこの記事に残す.

パッケージの定義とインポート

パッケージはソースファイルの先頭に配置する.

package my.demo

import kotlin.text.*

// ...

ディレクトリ名とパッケージ名は一致しなくてもよい.

プログラムのエントリーポイント

Kotlinのアプリケーションのエントリーポイントはmain関数である.

fun main() {
    println("Hello world!")
}

mainの別の形式は可変数のString型引数を受け取る.

fun main(args: Array<String>) {
    println(args.contentToString())
}

標準出力に出力する

printは引数を標準出力に出力する.

print("Hello ")
print("world!")
// Out: Hello world!

printlnは引数に改行を追加して表示する.

println("Hello world!")  // Out: Hello world!
println(42)              // OUt: 42

関数

2つのInt引数とInt戻り値を返す関数.

fun sum(a: Int, b: Int): Int {
    return a + b
}

fun main() {
    println(sum(3, 5))  // Out: 8
}

関数本体は式にすることができる.戻り値は推論される.

fun sum(a: Int, b: Int) = a + b

fun main() {
    println("sum of 19 and 23 is ${sum(19, 23)}")  // Out: sum of 19 and 23 is 42
}

意味のある値を返さない関数

fun printSum(a: Int, b: Int): Unit {
    println("sum of $a and $b is ${a + b}")
}

fun main() {
    printSum(-1, 8)  // Out: sum of -1 and 8 is 7
}

Unitは省略可能

fun printSum(a: Int, b: Int) {
    println("sum of $a and $b is ${a + b}")
}

変数

読み取りのみの変数をはvalキーワードで定義される.値を割り当ては1度のみ.

val a: Int = 1  // 即時代入
val b = 2       // `Int` 型が推論される
val c: Int      // 初期化子が指定されていない場合は型が必要.
c = 3           // 遅延割り当て

再代入できる変数はvarキーワードを使用する.

var x = 5 // `Int` 型が推論される
x += 1

最上位で変数を定義できる.

val PI = 3.14
var x = 0

fun incrementX() { 
    x += 1 
}

fun main() {
    println("x = $x; PI = $PI")  // Out: x = 0; PI = 3.14

    incrementX()
    println("x = $x; PI = $PI")  // Out: x = 1; PI = 3.14
}

クラスのインスタンス作成

classキーワードを使用してクラスを定義する.

class Shape

クラスのプロパティはその宣言または本体に記入できる.

class Rectangle(var height: Double, var length: Double) {
    var perimeter = (height + length) * 2
}

クラス宣言内に記入されたパラメータを持つデフォルトのコンストラクターは自動的に使用可能になる.

class Rectangle(var height: Double, var length: Double) {
    var perimeter = (height + length) * 2 
}
fun main() {
    val rectangle = Rectangle(5.0, 2.0)
    println("The perimeter is ${rectangle.perimeter}")  // Out: The perimeter is 14.0
}

クラス間の継承はコロン:で宣言する.クラスはデフォルトではfinal.継承クラスを作成するにはopenで宣言する.

open class Shape

class Rectangle(var height: Double, var length: Double): Shape() {
    var perimeter = (height + length) * 2
}

コメント

単一行と複数行のコメントが可能.

// This is an end-of-line comment

/* This is a block comment
   on multiple lines. */

ブロックコメントはネストできる

/* The comment starts here
/* contains a nested comment *⁠/
and ends here. */

文字列テンプレート

fun main() {
    var a = 1
    // 単純な名前
    val s1 = "a is $a" 

    a = 2
    // 任意の式
    val s2 = "${s1.replace("is", "was")}, but now is $a"
    println(s2)  // Out: a was 1, but now is 2
}

条件式

fun maxOf(a: Int, b: Int): Int {
    if (a > b) {
        return a
    } else {
        return b
    }
}

fun main() {
    println("max of 0 and 42 is ${maxOf(0, 42)}")  // Out: max of 0 and 42 is 42
}

Kotlinでは,ifも式として使用できる.

fun maxOf(a: Int, b: Int) = if (a > b) a else b

fun main() {
    println("max of 0 and 42 is ${maxOf(0, 42)}")  // Out: max of 0 and 42 is 42
}

forループ

リストの要素を取り出す.

fun main() {
    val items = listOf("apple", "banana", "kiwifruit")
    for (item in items) {
        println(item)
    }
}
Out:
apple
banana
kiwifruit

リストのインデックスを取り出す.

fun main() {
    val items = listOf("apple", "banana", "kiwifruit")
    for (index in items.indices) {
        println("item at $index is ${items[index]}")
    }
}
Out:
item at 0 is apple
item at 1 is banana
item at 2 is kiwifruit

whileループ

リストのサイズ数だけループ

fun main() {
    val items = listOf("apple", "banana", "kiwifruit")
    var index = 0
    while (index < items.size) {
        println("item at $index is ${items[index]}")
        index++
    }
}
Out:
item at 0 is apple
item at 1 is banana
item at 2 is kiwifruit

when式

fun describe(obj: Any): String =
    when (obj) {
        1          -> "One"
        "Hello"    -> "Greeting"
        is Long    -> "Long"
        !is String -> "Not a string"
        else       -> "Unknown"
    }

fun main() {
    println(describe(1))          // Out: One
    println(describe("Hello"))    // Out: Greeting
    println(describe(1000L))      // Out: Long
    println(describe(2))          // Out: Not a string
    println(describe("other"))    // Out: Unknown
}

範囲

in演算子を使用して数値が範囲内かチェックする.

fun main() {
    val x = 10
    val y = 9
    if (x in 1..y+1) {
        println("fits in range")  // Out: fits in range
    }
}

数値が範囲外かチェックする.

fun main() {
    val list = listOf("a", "b", "c")

    if (-1 !in 0..list.lastIndex) {    // True
        println("-1 is out of range")
    }
    if (list.size !in list.indices) {  // True
        println("list size is out of valid list indices range, too")
    }
}

範囲内を反復処理する

fun main() {
    for (x in 1..5) {
        print(x)  // Out: 12345
    }
}

一定の間隔スキップする

fun main() {
    for (x in 1..10 step 2) {
        print(x)  // Out: 13579
    }
    println()
    for (x in 9 downTo 0 step 3) {
        print(x)  // Out: 9630
    }
}

コレクション(List,Map,Array等のオブジェクトのこと)

コレクションを反復処理する.

fun main() {
    val items = listOf("apple", "banana", "kiwifruit")
    for (item in items) {
        println(item)
    }
}
Out:
apple
banana
kiwifruit

in演算子を使用してコレクションにオブジェクトが含まれているかをチェック.

fun main() {
    val items = setOf("apple", "banana", "kiwifruit")
    when {
        "orange" in items -> println("juicy")  // false
        "apple" in items -> println("apple is fine too")  // true
    }
}

ラムダ式を使用したコレクションのフィルタリングとマッピング

fun main() {
    val fruits = listOf("banana", "avocado", "apple", "kiwifruit")
    fruits
        .filter { it.startsWith("a") }  // aで始まる文字列のみ抽出
        .sortedBy { it }                // 昇順ソート
        .map { it.uppercase() }         // 大文字に変換
        .forEach { println(it) }        // 要素を出力
}
Out:
APPLE
AVOCADO

Null許容変数とnullチェック

Nullが可能である変数にはnullを許容することを示すマーク?を最後に着ける.
strが整数値を保持しない場合はnullを返す.

fun parseInt(str: String): Int? {
    // ...
}

null許容変数を返す関数を使用する.

fun parseInt(str: String): Int? {
    return str.toIntOrNull()
}

fun printProduct(arg1: String, arg2: String) {
    val x = parseInt(arg1)
    val y = parseInt(arg2)

    // x*yをするとnullが保持される可能性があるためエラーが発生.
    if (x != null && y != null) {
        // xとyはnullチェック後自動的にnull非許容にキャストされる.
        println(x * y)
    }
    else {
        println("'$arg1' or '$arg2' is not a number")
    }    
}

fun main() {
    printProduct("6", "7")  // Out: 42
    printProduct("a", "7")  // Out: 'a' or '7' is not a number
    printProduct("a", "b")  // Out: 'a' or 'b' is not a number
}

or

fun parseInt(str: String): Int? {
    return str.toIntOrNull()
}

fun printProduct(arg1: String, arg2: String) {
    val x = parseInt(arg1)
    val y = parseInt(arg2)
    
    // ...
    if (x == null) {
        println("Wrong number format in arg1: '$arg1'")
        return
    }
    if (y == null) {
        println("Wrong number format in arg2: '$arg2'")
        return
    }

    // x and y are automatically cast to non-nullable after null check
    println(x * y)
}

fun main() {
    printProduct("6", "7")  // Out: 42
    printProduct("a", "7")  // Out: Wrong number format in arg1: 'a'
    printProduct("a", "b")  // Wrong number format in arg2: 'b'
}

型チェックと自動キャスト

is演算子は式が型のインスタンスであるかどうかをチェックする.不変のローカル変数またはプロパティが特定の型かどうかチェックされる場合,それを明示的にキャストする必要はない.

fun getStringLength(obj: Any): Int? {
    if (obj is String) {
        // このブランチでは `obj` が自動的に `String` にキャストされる
        return obj.length
    }

    // `obj` は、型チェックされたブランチの外では依然として `Any` 型
    return null
}

fun main() {
    fun printLength(obj: Any) {
        println("Getting the length of '$obj'. Result: ${getStringLength(obj) ?: "Error: The object is not a string"} ")
    }
    printLength("Incomprehensibilities")
    printLength(1000)
    printLength(listOf(Any()))
}

or

fun getStringLength(obj: Any): Int? {
    if (obj !is String) return null

    // `obj` is automatically cast to `String` in this branch
    return obj.length
}

fun main() {
    fun printLength(obj: Any) {
        println("Getting the length of '$obj'. Result: ${getStringLength(obj) ?: "Error: The object is not a string"} ")
    }
    printLength("Incomprehensibilities")
    printLength(1000)
    printLength(listOf(Any()))
Out:
Getting the length of 'Incomprehensibilities'. Result: 21 
Getting the length of '1000'. Result: Error: The object is not a string 
Getting the length of '[java.lang.Object@66a29884]'. Result: Error: The object is not a string 

or even

fun getStringLength(obj: Any): Int? {
    // `obj` is automatically cast to `String` on the right-hand side of `&&`
    if (obj is String && obj.length > 0) {
        return obj.length
    }

    return null
}

fun main() {
    fun printLength(obj: Any) {
        println("Getting the length of '$obj'. Result: ${getStringLength(obj) ?: "Error: The object is not a string"} ")
    }
    printLength("Incomprehensibilities")
    printLength("")
    printLength(1000)
}
Out:
Getting the length of 'Incomprehensibilities'. Result: 21 
Getting the length of ''. Result: Error: The object is not a string 
Getting the length of '1000'. Result: Error: The object is not a string 
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?