woodi
왜 코틀린 인가? 본문
안드로이드 개발을 자바로만 개발하고 있지만 점점 코틀린에 대한 자료가 많아지면서 코틀린으로 학습하는것이 더 효율적이라고 느껴진다.
왜 코틀린이라는 언어가 나왔을까? 어떠한 장점이 있는지 살펴보자.
아래 안드로이드 공식 사이트에서 가져온 코틀린을 특징을 간략하게 설명하는 코드를 살펴보자.
예시 코드)
1. NullPointExceptions 에러 방지
- 자바에서 주로 발생되는 null 처리 에러를 ? 기호를 통해 변수 선언 시 사전에 방지가 가능하다.
2. 세미콜론 생략
- 자바와 다르게 세미콜론(";")을 생략이 가능하다.
3. 람다
- 람다를 사용하여 함수에 코드를 매개변수로 전달 할 수 있다.
4. 이름이 지정된 파라미터로 가독성 향상
- 파라미터에 이름을 지정해서 전달하는 방식으로 파라미터의 순서에 신경 쓸 필요가 없다.
5. 간편한 텍스트 출력방식
- $ 기호를 사용하여 변수명을 간편하게 출력 할 수 있다.
이번에는 아래 코틀린 공식사이트에는 다음과 같은 코틀린의 장점을 살펴보자.
1. 간결하다.
2. 안전하다.
3. 표현력이 높다.
4. 상호운용가능하다.
5. 멀티플랫폼지원이 가능하다.
간결하다.
- data class 사용 시 자동으로 생성되는 함수들로인해 자바에 비해 데이터 클래스 선언이 간편하다.
- singletone 사용 시 object로 선언하면 간편하게 사용이 가능하다.
- new 를 생략하여 객채생성이 가능하다.
data class Employee(
val name: String,
val email: String,
val company: String
) // + automatically generated equals(), hashCode(), toString(), and copy()
object MyCompany { // A singleton
const val name: String = "MyCompany"
}
fun main() { // Function at the top level
val employee = Employee("Alice", // No `new` keyword
"alice@mycompany.com", MyCompany.name)
println(employee)
}
안전하다.
- ? 기호를 사용하여 미리 Null 에러를 방지한다.
- 언제든지 throw 예외로 처리가 가능하다.
- 컴파일러는 print로 출력시에 자동으로 문자열 캐스팅을 지원한다.
fun reply(condition: Boolean): String? = // Nullability is part of Kotlin’s type system
if (condition) "I'm fine" else null
fun error(): Nothing = // Always throw an exception
throw IllegalStateException("Shouldn't be here")
fun main() {
val condition = true // Try replacing `true` with `false` and run the sample!
val message = reply(condition) // The result is nullable
// println(message.uppercase()) // This line doesn't compile
println(message?.replace("fine", "okay")) // Access a nullable value in a safe manner
if (message != null) { // If you check that the type is right,
println(message.uppercase()) // the compiler will smart-cast it for you
}
val nonNull: String = // If the null-case throws an error,
reply(condition = true) ?: error() // Kotlin can infer that the result is non-null
println(nonNull)
}
표현력이 우수하다.
- 함수를 단 한줄로 표현이 가능하다.
- 값이 true일 때만 처리하도록 가능하다.
- swift 코드의 guard 와 비슷하게 반드시 null 이 아닌경우에 처리하도록 가능하다.
val map = mapOf(1 to "one", 2 to "two")
for ((k, v) in map) { // Traverse a map or a list of pairs
println("$k -> $v")
}
fun obtainKnowledge() = Pair("The Answer", 42) // Single-expression functions
val (description, answer) = obtainKnowledge() // Destructure into a pair of two variables
println("$description: $answer")
getText()?.let { // Apply an action to a nullable expression
sendEmailTo("alice@example.com", it) // if it’s not null
}
createEmptyWindow()
.apply { // Configure properties of an object
width = 300
height = 200
isVisible = true
}.also { w -> // Perform an additional operation on a call chain
showWindow(w)
}
val fixedIssue = issueById["13456"]
?.takeIf { it.status == Status.FIXED } // Use the value only if the condition is true
println(fixedIssue)
상호운용성이 좋다.
- 자바 또는 웹 프로젝트에서도 코틀린 코드 사용이 가능하므로 활용도가 높다.
// Use any existing JVM library or framework
// Call Kotlin code from Java without an issue
@SpringBootApplication
class DemoApplication
fun main(args: Array<String>) {
runApplication<DemoApplication>(*args)
}
@RestController
class MessageResource {
@GetMapping
fun index(): List<Message> = listOf(
Message("1", "Hello!"),
Message("2", "Bonjour!"),
Message("3", "Privet!"),
)
}
data class Message(val id: String?, val text: String)
// Write Kotlin code, compile it to JavaScript, and run it in the browser
// Use existing JavaScript APIs and libraries
import kotlinx.browser.window
fun main() {
val body = window.document.body
body?.innerHTML += "<b>Hello, <i>Kotlin</i></b>"
window.setInterval({
body?.innerHTML += "!"
}, 1000)
}
// Use Kotlin wrappers to build applications with JavaScript frameworks such as React
import react.*
import react.dom.*
import kotlinx.html.js.onClickFunction
val counter = functionalComponent<Props> {
val (count, setCount) = useState(0)
button {
attrs.onClickFunction = { setCount(count + 1) }
+count.toString()
}
}
멀티플랫폼 지원가능하다.
- Kotlin은 다양한 플랫폼(Android, iOS, Web)에서 공통적으로 코드를 정의해서 플랫폼에 특화된 활용이 가능하다.
// Common
// Declare signatures to use them in the common code
// Provide platform-specific implementations in the platform modules
expect fun randomUUID(): String
expect class PlatformSocket(
url: String
) {
fun openSocket(listener: PlatformSocketListener)
fun closeSocket(code: Int, reason: String)
fun sendMessage(msg: String)
}
interface PlatformSocketListener {
fun onOpen()
fun onFailure(t: Throwable)
fun onMessage(msg: String)
fun onClosing(code: Int, reason: String)
}
import java.util.*
actual fun randomUUID() = UUID.randomUUID().toString()
actual class PlatformSocket actual constructor(url: String) {
// Use okhttp3 in implementation
}
// iOS
import platform.Foundation.NSUUID
actual fun randomUUID(): String = NSUUID().UUIDString()
actual class PlatformSocket actual constructor(url: String) {
// Use platform.Foundation in implementation
}
'Language' 카테고리의 다른 글
Kotlin - 문(statement)과 식(experssion)의 구분 (0) | 2023.05.09 |
---|---|
Clean Code - DRY (0) | 2022.12.05 |