ほのかちゃん

てっとりばやくWindowsのコマンドラインで

インストール

  1. Kotlinのコンパイラをインストール(→ Working with the Command Line Compiler
  2. 未インストールなら Java実行環境 も用意(Java 8でOK)
PS W:\> kotlinc -version
info: kotlinc-jvm 1.3.21 (JRE 1.8.0_201-b09)

わざわざ手元にインストールしないで Kotlin Playground を使わせてもらうのでもいいかも

Hello

#highlight(kt){{
fun main(args: Array<String>) {
println("Hello, again my old dear place")
}
}}

PS W:\> kotlinc .\hello.kt -include-runtime -d hello.jar
PS W:\> java -jar hello.jar
Hello, again my old dear place

ぬるぽ

#highlight(kt){{
import java.util.Date
import java.text.SimpleDateFormat;

class Person {
val firstName: String
val lastName: String
val birthday: Date?

// "?"がついていなければ null 入れるコードはコンパイルすらできない
constructor(firstName: String, lastName: String, birthday: Date?) {
this.firstName = firstName
this.lastName = lastName
this.birthday = birthday
}

fun fullName(): String {
return "%s %s".format(this.firstName, this.lastName)
}

// 誕生日が null なら何も計算せず(letの中に入らず)に null だけ返す
// 整数型もオブジェクトのように扱えて、null にもできる
fun age(): Int? {
return this.birthday?.let {
val sdf = SimpleDateFormat("yyyyMMdd")
(sdf.format(Date()).toInt() - sdf.format(it).toInt()) / 10000
}
}
}

fun main(args: Array<String>) {
val person1 = Person("Kanata", "Tanaka", SimpleDateFormat("yyyy/MM/dd").parse("2013/12/02"))
println("%s (%s)".format(person1.fullName(), person1.age()?.toString()))

val person2 = Person("Kanata", "Tanaka", null)
// SQLのCOALESCE関数みたいなもの
println("%s (%s)".format(person2.fullName(), person2.age()?.toString() ?: "?"))
}
}}

PS W:\> kotlinc .\age.kt -include-runtime -d age.jar
PS W:\> java -jar age.jar
Kanata Tanaka (5)
Kanata Tanaka (?)

#highlight(end)


トップ   新規 一覧 検索 最終更新   ヘルプ   最終更新のRSS