728x90
참고 : Basic syntax | Kotlin Documentation (kotlinlang.org)
Basic syntax | Kotlin
kotlinlang.org
1. Package & imports
package my.demo
import kotlin.text.*
2. 시작 지점
- main 함수
fun main() {
println("Hello world!")
}
// String 인자들을 받는 형태
fun main(args: Array<String>) {
println(args.contentToString())
}
3. 콘솔 출력
- 줄바꿈이 있는 없는 것과 있는 것
print("줄바꿈X")
println("줄바꿈O")
4. 함수
- 반환 타입 생략 가능(알아서 추론함) & 축약 가능
fun sum(a: Int, b: Int): Int {
return a + b
}
fun sum(a: Int, b: Int) = a + b
- Unit은 Java의 void와 비슷한 개념으로 생략가능
fun printSum(a: Int, b: Int): Unit {
println("sum of $a and $b is ${a + b}")
}
fun printSum(a: Int, b: Int) {
println("sum of $a and $b is ${a + b}")
}
5. 변수
- val은 read only. 한번만 할당 가능
- var는 재할당 가능.
val a: Int = 1 // 즉시 할당
val b = 2 // 타입 자동 추론(Int)
val c: Int // 즉시 할당이 없으면 타입 지정 필요
c = 3 // 선언 후 할당
var x = 5 // 타입 자동 추론(Int)
x += 1
6. 클래스
- class 키워드를 사용
class Shape
- 선언문 또는 body에 속성 명시 가능
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}")
- 콜론으로 class간 상속 가능. class 들은 불변하다. open 명령어로 class를 상속가능하게 만들고 상속해야 함
open class Shape
class Rectangle(var height: Double, var length: Double): Shape() {
var perimeter = (height + length) * 2
}
7. 주석처리
- 한줄처리와 여러줄 처리
// 한줄
/*
여러줄
*/
- 주석 중첩 가능
/* The comment starts here
/* contains a nested comment */
and ends here. */
8. 문자 템플릿
- 간단한 변수 ( $ 사용 )
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"
9. 조건식
- if문이 표현식으로 쓰일 수 있음
전
fun maxOf(a: Int, b: Int): Int {
if (a > b) {
return a
} else {
return b
}
}
후
fun maxOf(a: Int, b: Int) = if (a > b) a else b
10. 반복문
val items = listOf("apple", "banana", "kiwifruit")
for (item in items) {
println(item)
}
또는
val items = listOf("apple", "banana", "kiwifruit")
for (index in items.indices) {
println("item at $index is ${items[index]}")
}
11. when 표현식
- Java의 switch 같은 기능
fun describe(obj: Any): String =
when (obj) {
1 -> "One"
"Hello" -> "Greeting"
is Long -> "Long"
!is String -> "Not a string"
else -> "Unknown"
}
12. Ranges
- 숫자 범위 in 확인
val x = 10
val y = 9
if (x in 1..y+1) {
println("fits in range")
}
- 숫자 범위 out 확인
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")
}
- 반복문 범위 사용
for (x in 1..5) {
print(x)
}
- 반복문 범위 사용(점프)
for (x in 1..10 step 2) {
print(x)
}
println()
for (x in 9 downTo 0 step 3) {
print(x)
}
13. Collections
- 컬렉션 반복
for (item in items) {
println(item)
}
- 컬렉션에 존재 여부 확인
when {
"orange" in items -> println("juicy")
"apple" in items -> println("apple is fine too")
}
- filter 와 map
val fruits = listOf("banana", "avocado", "apple", "kiwifruit")
fruits
.filter { it.startsWith("a") }
.sortedBy { it }
.map { it.uppercase() }
.forEach { println(it) }
14. Nullablle & null check
- Nullable은 '?' 표시를 해줘야 함
fun parseInt(str: String): Int? {
return str.toIntOrNull()
}
- null check 를 하면 이후 로직은 non-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")
}
}
또는
// ...
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)
15. 타입 체크, 자동 변환
- '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
}
또는
fun getStringLength(obj: Any): Int? {
if (obj !is String) return null
// `obj` is automatically cast to `String` in this branch
return obj.length
}
728x90
댓글