Kotlin은 다양한 기능을 간단하게 사용할 수 있습니다.
오늘은 코틀린의 주요 기능과 코드를 알아보겠습니다.
코틀린은 변수 선언부터 반복문까지 간단하게 구현할 수 있습니다.
fun main() {
val name = "stranger" // Declare your first variable
println("Hi, $name!") // ...and use it!
print("Current count:")
for (i in 0..10) { // Loop over a range from 0 to 10
print(" $i")
}
}
비동기 방식의 코드 예제입니다.
코틀린을 활용하면 간단하게 지연 처리가 가능합니다.
import kotlinx.coroutines.*
suspend fun main() { // A function that can be suspended and resumed later
val start = System.currentTimeMillis()
coroutineScope { // Create a scope for starting coroutines
for (i in 1..10) {
launch { // Start 10 concurrent tasks
delay(3000L - i * 300) // Pause their execution
log(start, "Countdown: $i")
}
}
}
// Execution continues when all coroutines in the scope have finished
log(start, "Liftoff!")
}
fun log(start: Long, msg: String) {
println("$msg " +
"(on ${Thread.currentThread().name}) " +
"after ${(System.currentTimeMillis() - start)/1000F}s")
}
객체 간의 관계를 손 쉽게 정의하고 구현할 수 있습니다.
abstract class Person(val name: String) {
abstract fun greet()
}
interface FoodConsumer {
fun eat()
fun pay(amount: Int) = println("Delicious! Here's $amount bucks!")
}
class RestaurantCustomer(name: String, val dish: String) : Person(name), FoodConsumer {
fun order() = println("$dish, please!")
override fun eat() = println("*Eats $dish*")
override fun greet() = println("It's me, $name.")
}
fun main() {
val sam = RestaurantCustomer("Sam", "Mixed salad")
sam.greet() // An implementation of an abstract function
sam.order() // A member function
sam.eat() // An implementation of an interface function
sam.pay(10) // A default implementation in an interface
}
클래스와 리스트를 간단하게 규정할 수 있고, 람다식을 활용해서 간편하게 조회할 수 있습니다.
fun main() {
// Who sent the most messages?
val frequentSender = messages
.groupBy(Message::sender)
.maxByOrNull { (_, messages) -> messages.size }
?.key // Get their names
println(frequentSender) // [Ma]
// Who are the senders?
val senders = messages
.asSequence() // Make operations lazy (for a long call chain)
.filter { it.body.isNotBlank() && !it.isRead } // Use lambdas...
.map(Message::sender) // ...or member references
.distinct()
.sorted()
.toList() // Convert sequence back to a list to get a result
println(senders) // [Adam, Ma]
}
data class Message( // Create a data class
val sender: String,
val body: String,
val isRead: Boolean = false, // Provide a default value for the argument
)
val messages = listOf( // Create a list
Message("Ma", "Hey! Where are you?"),
Message("Adam", "Everything going according to plan today?"),
Message("Ma", "Please reply. I've lost you!"),
)
JUnit과 코틀린 테스트 패키지를 활용해서 간편하게 테스트 할 수 있습니다.
// Tests
// The following example works for JVM only
import org.junit.Test
import kotlin.test.*
class SampleTest {
@Test
fun `test sum`() { // Write test names with whitespaces in backticks
val a = 1
val b = 41
assertEquals(42, sum(a, b), "Wrong result for sum($a, $b)")
}
@Test
fun `test computation`() {
assertTrue("Computation failed") {
setup() // Use lambda returning the test subject
compute()
}
}
}
// Sources
fun sum(a: Int, b: Int) = a + b
fun setup() {}
fun compute() = true