•
패키지 명세는 소스 파일의 상단에 있어야한다.
•
디렉토리와 패키지를 일치시킬 필요는 없고 소스 파일은 파일 시스템에 임의로 배치될 수 있다.
package my.demo
import kotlin.text.*
// ...
Kotlin
복사
Program Entry Point
•
Kotlin 어플리케이션의 진입점은 main 함수
•
main 함수는 가변적인 개수의 String 인수를 허용한다.
fun main(args: Array<String>) {
println(args.contentToString())
}
Kotlin
복사
Print to the standard output
•
print() 를 통해 인수를 표준 출력에 내보낸다.
•
println() 을 통해 인수를 표준 출력에 내보내고 줄 바꿈을 추가한다.
print("Hello ")
print("world!")
println("Hello world!")
println(42)
Kotlin
복사
Read from the standard input
•
readln() 을 통해 인수를 표준 입력에서 읽는다.
// Prints a message to request input
println("Enter any word: ")
// Reads and stores the user input. For example: Happiness
val yourWord = readln()
// Prints a message with the input
print("You entered the word: ")
print(yourWord)
// You entered the word: Happiness
Kotlin
복사
Functions
•
fun 은 함수를 명시
•
함수 본문은 표현식이 될 수 있고 반환 타입은 추론된다.
•
Unit 반환 타입은 생략이 가능하다.
//반환 타입 지정
fun sum(a: Int, b: Int): Int {
return a + b
}
//함수 본문을 표현식으로 사용
fun sum(a: Int, b: Int) = a + b
//Unit 타입 생략
fun printSum(a: Int, b: Int) {
println("sum of $a and $b is ${a + b}")
}
Kotlin
복사
Variables
•
val 은 read-only 변수를 명시
•
var 은 mutable 변수를 명시
•
= 를 통해 변수에 값을 할당
val popcorn = 5 // There are 5 boxes of popcorn
val hotdog = 7 // There are 7 hotdogs
var customers : Int = 10 // There are 10 customers in the queue
// Some customers leave the queue
customers = 8
println(customers) // 8
Kotlin
복사
Creating classes and instances
•
class 키워드를 사용해서 클래스를 정의
•
클래스의 속성은 선언이나 본문에 나열될 수 있다.
•
클래스 선언에 나열된 매개변수가 있는 기본 생성자는 자동으로 사용할 수 있다.
•
클래스 간 상속은 : 으로 선언한다.
•
클래스는 기본적으로 final이므로 상속 가능하게 하려면 open 키워드를 사용해야한다.
//클래스 정의 예제
class Rectangle(val height: Double, val length: Double) {
val perimeter = (height + length) * 2
}
//클래스 상속 예제
open class Shape
class Rectangle(val height: Double, val length: Double): Shape() {
val perimeter = (height + length) * 2
}
Kotlin
복사
Comments
•
단일 줄 (또는 줄 끝) 주석과 다중 줄 (블럭) 주석을 지원한다.
•
Kotlin의 블록 주석은 중첩될 수 있다.
// 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. */
Kotlin
복사