Kotlin 構文1

変数

fun main(args: Array<String>){
  val msg: String = "Hello World"
  println(msg)
}

データ型

  val msg: String = "Hello World"
  val c: Char = 'a'
  val i: Int = 100
  val l: Long = 555555555555L
  val d: Double = 234.352
  val f: Float = 123.345
  val flag: Boolean = true

データ演算

val x = 10
  println(x / 3)
  println(x / 3.0)
  println(x % 3)
  var y = 5
  y++
  y--
  println(y)
  var z = 4
  z += 12
  println(z)
  val flag = true
  println(!flag)

文字列

  println("hello " + "world")

  val name = "yoshimoto"
  println("my name is $name")
  println("my score is ${12 + 43}")

  println("hello\n worl\td")

ifの条件分岐

val score = 85
  if (score > 80){
    println("Great!")
  } elseif (score > 60){
      println("good!")
  } else {
    println("soso ..")
  }

when 条件分岐

val num = 3
  when (num){
    0 -> println("zero")
    1 -> println("one")
    in 4.. 10 -> println("many")
    else -> println("other")
  }

while, for

var i = 0
  while (i < 10){
    println("loop: $i")
    i++
  }
for (i in 0..9){
    println(i)
  }

関数

fun sayHi(name: String = "tebes", age: Int = 23){
  println("hi! $name ($age)")
}

fun main(args: Array<String>){
  sayHi("tom", 22)
  sayHi()
}

関数の返り値

fun sayHi(): String {
  return "hi!"
}

fun main(args: Array<String>){
  val msg = sayHi()
  println(msg)
}

class

class User {
  var name = "me!"
  fun sayHi(){
    println("hi $name")
  }
}

fun main(args: Array<String>){
  val user = User() // インスタンス
  println(user.name)
  user.sayHi()
}

コンストラクタ引数

class User(var name: String) { //コンストラクタ引数
  /*var name = name*/
  var team = "red"
  init {
    println("instance created: name: $name, team: $team")
  }
  fun sayHi(){
    println("hi $name")
  }
}

fun main(args: Array<String>){
  val tom = User("tom")
  println(tom.name)
  tom.sayHi()
}