- java_to_kotlin
- Docker
- 리믹스아이콘
- 폰트어썸
- 전략패턴
- oraclejdk
- 도커
- QueryDSL
- Spring Cloud
- arc browser
- 라즈베리파이 클러스터
- remix icon
- Openjdk
- 옵저버패턴
- springboot
- OneToMany
- EntityGraph
- openapispec
- restdocs
- 디자인패턴
- Observer Pattern
- fontawesome
- with jdk
- kotlin
- 라즈베리파이
- spring cloud contract
- 무료 아이콘 폰트
- restcontroller
- java
- Spring
- Today
- Total
< Dev-Kidult />
Java to kotlin - 0. kotlin? 본문
시작
우리가 지금 주로 쓰고 있는 IDE Intelij를 만든 Jetbrains에서 2011년에 발표되었고, 2017년 구글에서 안드로이드 공식언어로 지정되어 쓰고 있는만큼 많은 관심을 받고 있는 언어이다.
왜?
우리는 왜 코틀린을 써야하는가.
코틀린 공식 홈페이지에서 그들은 코틀린을 현대적이고, 간결하며, 안전한 프로그래밍 언어라고 설명하고 있다.
그 특징을 보여줄 수 있는 예제로 시작해보자.
간결성
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)
}
안정성
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)
}
표현가능성
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)
특성
1. 코틀린은 멀티플랫포머 언어다.
당연히 우리가 쓰려고 하는 서버사이드 부분에서도 사용을 할 수 있고, 안드로이드 그리고 또 iOS에서도 사용을 할 수 있다.
그리고 맥OS, 리눅스, 윈도우에서도 사용이 가능하며, 심지어 자바스크립트로도 사용이 가능하다.
Get started with Kotlin/JS for React 해당 예제에 코틀린으로 react를 쓰는법도 나와있다.
2. 정작 타입 지정 언어다.
자바와 마찬가지로 코틀린도 정적 타입 지정 언어다.
이말은 곧 컴파일 시점에서 모든구성요소의 타입을 확인 할 수 있고, 오류를 막아줄 수 있다는 뜻이다.
3. 함수형 프로그래밍
일급 시민인 함수
함수(프로그램의 행동을 나타내는 코드 조각)를 일반 값처럼 다룰 수 있다. 함수를 변수에 저장할 수 있고, 함수를 인자로 다른 함수에 전달할 수 있으며, 함수에서 새로운 함수를 만들어서 반환할 수 있다.
불변성
함수형 프로그래밍에서는 일단 만들어지고 나면 내부 상태가 절대로 바뀌지 않는 불변 객체를 사용해 프로그램을 작성한다.
부수 효과(side effect) 없음
함수형 프로그래밍에서는 입력이 같으면 항상 같은 출력을 내놓고 다른 객체의 상태를 변경하지 않으며, 함수 외부나 다른 바깥 환경과 상호작용하지 않는 순수 함수를 사용한다.
3-1. 함수형 스타일로 작성하면 어떤 유익이 있을까?
첫째로 간결성을 들 수 있다.
함수형 코드는 그에 상응하는 명령형 코드에 비해 더 간결하며 우아하다. (순수) 함수를 값처럼 활용할 수 있으면 더 강력한 추상화를 할 수 있고 강력한 추상화를 사용해 코드 중복을 막을 수 있다.
두번째로 다중 스레드를 사용해도 안전하다.
다중 스레드 프로그램에서는 적절한 동기화 없이 같은 데이터를 여러 스레드가 변경하는 경우 가장 많은 문제가 생긴다. 불변 데이터 구조를 사용하고 순수 함수를 그 데이터 구조에 적용한다면 다중 스레드 환경에서 같은 데이터를 여러 스레드가 변경할 수 없다. 따라서 복잡한 동기화를 적용하지 않아도 된다.
마지막으로 함수형 프로그램은 테스트하기 쉽다.
부수 효과가 있는 함수는 그 함수를 실행할 때 필요한 전체 환경을 구성하는 준비 코드가 따로 필요하지만, 순수 함수는 그런 준비 코드 없이 독립적으로 테스트할 수 있다.
'개발 > Back-end' 카테고리의 다른 글
| Java to Kotlin - 2. 조건문과 반복문 (0) | 2022.12.28 |
|---|---|
| Java to Kotlin - 1. 코틀린의 타입 시스템 (0) | 2022.12.28 |
| Springboot - QueryBinder (0) | 2022.12.28 |
| Spring boot JPA Specification + Spring filter 파라미터로 쉽게 조회하기 (0) | 2022.04.21 |
| `Spring cloud contract` 를 배워보자 (0) | 2020.08.14 |