코틀린 문법에 맞게 개발하다보면 ‘코틀린스러워’진다!
✔️ Kotlin ByteCode 변환
Show Kotlin ByteCode
→ Decompile
을 통해 Java 코드로 변환 가능 val add1 = { a: Int, b: Int -> a + b }
val add2: (Int, Int) -> Int = { a, b -> a + b }
val sum = add1(3, 7)
fun operate(op: (Int, Int) -> Int): Int {
return op(3, 10)
}
fun operate(op: (Int, Int) -> Int): (Int, Int) -> Int {
return op
}
val lambda = { a: Int, b: Int -> a + b}
val student = Student("name", 20, "won") // not null
val studentNull: Student? = null // nullable
println(student.name)
println(studentNull.name) // Error
new
키워드 사용하지 않음toString()
, equals()
, hashCode()
자동 생성 class Student(String name) {
// 클래스 내에서 함수 정의
fun print() {
}
companion object{
// name에 접근 못함
// static 영역(정적 팩토리 메서드 만들때)
}
}
🤔 나의 질문
Q. companion object
가 static
영역이면 상수 선언할 때도 사용되나요?
A. const val
키워드를 제공한다!
companion object {
const val SCHOOL_NAME = "Kotlin Academy"
}
open
키워드를 붙여야 상속 가능interface
지원val students = listOf(Student("gom", 20), Student("won", 22))
val studentMap = students.associate { it.age to it.name }
?.run
과 같이 nullable 타입과 함께 사용하면 안전하게 실행 가능)?.let
)이나 특정 프로퍼티를 활용한 작업에 유용. val sting = students.map { it.name }.joinToString(",")
// 커스텀해서 사용 가능
fun <T> Collection<T>.toCommaString(): STring = this.joinToSTring(",")
- infix 연산자
- 두 개 사이에서 동작하게 할 수 있음