출처 링크:https://kotlinlang.org/docs/basic-syntax.html
패키지 정의 및 가져오기
패키지 사양은 소스 파일의 맨 위에 있어야 합니다.
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!")
println 인수를 인쇄하고 줄 바꿈을 추가하여 다음에 인쇄하는 항목이 다음 줄에 표시되도록 합니다.
println("Hello world!")
println(42)
기능
두 개의 Int매개변수와 Int반환 유형이 있는 함수입니다 .
fun sum(a: Int, b: Int): Int {
return a + b
}
함수 본문은 표현식이 될 수 있습니다. 반환 유형이 유추됩니다.
fun sum(a: Int, b: Int) = a + b
의미 있는 값을 반환하지 않는 함수입니다.
fun printSum(a: Int, b: Int): Unit {
println("sum of $a and $b is ${a + b}")
}
Unit 반환 유형은 생략할 수 있습니다. (위 코드와 같다고 보면 됨)
fun printSum(a: Int, b: Int) {
println("sum of $a and $b is ${a + b}")
}
Unit이란?
Unit은 흔히 함수의 반환 구문이 없다는 것을 표현하기 위해 사용
01 fun myFun1() { }
02 fun myFun2(): Unit { }
위 코드에서 myFun1( ) 함수를 선언했습니다. 이 함수에는 return 구문이 없습니다. 딱히 반환할 데이터가 없다는 것입니다. 함수는 함수 선언 부분에 콜론(:)으로 구분해서 함수의 반환 타입을 명시해야 하는데 선언하지 않았습니다. 그러면 기본으로 Unit으로 선언한 것과 같습니다. 그러므로 01번 줄의 함수 선언은 02번 줄의 Unit으로 반환 타입을 명시한 선언과 같습니다. 이처럼 Unit을 반환 타입으로 사용하는 함수는 함수에서 의미 있는 반환값이 없다는 의미이므로 자바의 void와 비슷하다고 이야기할 수 있습니다.
출처: https://kkangsnote.tistory.com/64 [깡샘의 토마토]
변수
읽기 전용 지역 변수는 키워드를 사용하여 정의됩니다 val. 한 번만 값을 할당할 수 있습니다.
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키워드를 사용합니다 .
var x = 5 // `Int` type is inferred
x += 1
최상위 수준에서 변수를 선언할 수 있습니다.
val PI = 3.14
var x = 0
fun incrementX() {
x += 1
}
클래스 및 인스턴스 생성
클래스를 정의하려면 class키워드를 사용하십시오 .
class Shape
클래스의 속성은 선언 또는 본문에 나열될 수 있습니다.
class Rectangle(var height: Double, var length: Double) {
var perimeter = (height + length) * 2
}
클래스 선언에 나열된 매개변수가 있는 기본 생성자는 자동으로 사용할 수 있습니다.
val rectangle = Rectangle(5.0, 2.0)
println("The perimeter is ${rectangle.perimeter}")
클래스 간의 상속은 콜론( :)으로 선언됩니다 . 클래스는 기본적으로 final입니다. 클래스를 상속 가능하게 만들려면 open으로 표시하십시오.
open class Shape
class Rectangle(var height: Double, var length: Double): Shape() {
var perimeter = (height + length) * 2
}
코멘트
대부분의 최신 언어와 마찬가지로 Kotlin은 한 줄(또는 줄 끝 ) 및 여러 줄( 블록 ) 주석을 지원합니다.
// This is an end-of-line comment
/* This is a block comment
on multiple lines. */
Kotlin의 블록 주석은 중첩될 수 있습니다.
/* The comment starts here
/* contains a nested comment */
and ends here. */
문자열 템플릿
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"
문자열 리터럴에는 템플릿 표현식이 포함될 수 있습니다 . 템플릿 표현식은 달러 기호( $)로 시작하고 다음 이름 중 하나로 구성됩니다.
val i = 10
println("i = $i") // prints "i = 10"
또는 중괄호로 묶인 표현식:
val s = "abc"
println("$s.length is ${s.length}") // prints "abc.length is 3"
원시 문자열과 이스케이프 문자열 모두에서 템플릿을 사용할 수 있습니다. 식별자$ 의 시작으로 허용되는 기호 앞에 원시 문자열(백슬래시 이스케이프를 지원하지 않음)에 문자 를 삽입하려면 다음 구문을 사용하십시오.
val price = """
${'$'}_9.99
"""
조건식
fun maxOf(a: Int, b: Int): Int {
if (a > b) {
return a
} else {
return b
}
}
Kotlin에서는 if표현식으로도 사용할 수 있습니다.
fun maxOf(a: Int, b: Int) = if (a > b) a else b
for 루프
val items = listOf("apple", "banana", "kiwifruit")
for (item in items) {
println(item)
}
결과값: apple banana kiwifruit
val items = listOf("apple", "banana", "kiwifruit")
for (index in items.indices) {
println("item at $index is ${items[index]}")
}
결과값:
item at 0 is apple
item at 1 is banana
item at 2 is kiwifruit
While루프
val items = listOf("apple", "banana", "kiwifruit")
var index = 0
while (index < items.size) {
println("item at $index is ${items[index]}")
index++
}
결과값:
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"
}
결과값:
One
Greeting
Long
Not a string
Unknown
범위 (Ranges)
in연산자를 사용하여 숫자가 범위 내에 있는지 확인하십시오 .
val x = 10
val y = 9
if (x in 1..y+1) {
println("fits in range")
}
결과값: fits in range
숫자가 범위를 벗어났는지 확인합니다.
val list = listOf("a", "b", "c")
if (-1 !in 0..list.lastIndex) {
println("-1 is out of range")
}
if (list.size !in list.indices) {
println("list size is out of valid list indices range, too")
}
결과값:
-1 is out of range
list size is out of valid list indices range, too
범위를 반복합니다.
for (x in 1..5) {
print(x)
}
결과값:12345
또는 진행 이상.
for (x in 1..10 step 2) {
print(x)
}
println()
for (x in 9 downTo 0 step 3) {
print(x)
}
결과값:
13579
9630
컬렉션
컬렉션을 반복합니다.
for (item in items) {
println(item)
}
결과값:
apple
banana
kiwifruit
in연산자를 사용하여 컬렉션에 개체가 포함되어 있는지 확인합니다 .
when {
"orange" in items -> println("juicy")
"apple" in items -> println("apple is fine too")
}
결과값:apple is fine too
람다 식을 사용하여 컬렉션 필터링 및 매핑:
val fruits = listOf("banana", "avocado", "apple", "kiwifruit")
fruits
.filter { it.startsWith("a") }
.sortedBy { it }
.map { it.uppercase() }
.forEach { println(it) }
결과값:
APPLE
AVOCADO
Nullable 값 및 Null 검사
null값이 가능할 때 참조는 명시적으로 nullable로 표시되어야 합니다. Nullable 형식 이름은 ?끝에 있습니다.
반환 null하는 경우 str정수를 보유하지 않습니다
fun parseInt(str: String): Int? {
// ...
}
nullable 값을 반환하는 함수 사용:
fun printProduct(arg1: String, arg2: String) {
val x = parseInt(arg1)
val y = parseInt(arg2)
// Using `x * y` yields error because they may hold nulls.
if (x != null && y != null) {
// x and y are automatically cast to non-nullable after null check
println(x * y)
}
else {
println("'$arg1' or '$arg2' is not a number")
}
}
결과값:
42
'a' or '7' is not a number
'a' or 'b' is not a number
또는
// ...
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)
결과값: 42
Wrong number format in arg1: 'a'
Wrong number format in arg2: 'b'
유형 검사 및 자동 캐스트
is연산자 검사되는 식 타입의 인스턴스의 경우. 변경할 수 없는 지역 변수나 속성이 특정 유형에 대해 확인된 경우 명시적으로 캐스팅할 필요가 없습니다.
fun getStringLength(obj: Any): Int? {
if (obj is String) {
// `obj` is automatically cast to `String` in this branch
return obj.length
}
// `obj` is still of type `Any` outside of the type-checked branch
return null
}
결과값:
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@2a84aee7]'. Result: Error: The object is not a string
또는
fun getStringLength(obj: Any): Int? {
if (obj !is String) return null
// `obj` is automatically cast to `String` in this branch
return obj.length
}
결과값:
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@2a84aee7]'. Result: Error: The object is not a string
또는
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
}
결과값:
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