val array: Array<Int> = arrayOf(100, 200)
for (i in array.indices) {
println("${i} ${array[i]}")
}
for ((idx, value) in array.withIndex()) {
println("$idx $value")
}
array.plus(300)
val numbers = listOf(100, 200) // 불변 리스트
val emptyList = emptyList<Int>() // 타입 추론이 되지 않는 경우 명시
numbers.get(0)
numbers[0]
for (number in numbers) {
println(number)
}
for ((idx, value) in numbers.withIndex()) {
println("${idx} ${value}")
}
val numbers2 = mutableListOf(100, 200)
numbers.add(300)
val oldMap = mutableMapOf<Int, String>()
oldMap[1] = "MONDAY"
oldMap[2] = "TUESDAY"
mapOf(1 to "MONDAY", 2 to "TUESDAY")
for (key in oldMap.keys) {
println(key)
println(oldMap[key])
}
for ((key, value) in oldMap.entries) {
println(key)
println(value)
}
fun main() {
val str = "ABC"
println(str.lastChar())
}
fun String.lastChar(): Char {
return this[this.length - 1]
}
fun 확장하려는클래스(수신객체타입).함수이름(파라미터): 리턴타입 {
// this(수신객체)를 이용해 실제 클래스 안의 값에 접근
}
fun String.lastChar(): Char {
return this[this.length - ]
}
val String.lastChar: Char {
get() = this[this.length - 1]
fun Int.add(other: Int): Int {
return this + other
}
infix fun Int.add2(other: Int): Int {
return this + other
}
3.add(4)
3.add2(4)
3 add2 4
fun main() {
3.add(4)
}
inline fun Int.add(other: Int): Int {
return this + other
}
fun createPerson(firstName: String, lastName: String): Person {
fun validate(name: String, fieldName: String) {
if (name.isEmpty()) {
throw IllegalArgumentException("${fieldName}은 비어 있을 수 없습니다! 현재 값 : $name")
}
}
validateName(firstName, "firstName")
validateName(lastName, "lastName")
return Person(firstName, lastName, 1)
}
private List<Fruit> filterFruit(List<Fruit> fruits, Predicate<Fruit> fruitFilter) {
return fruits.stream()
.filter(fruitFilter)
.collect(Collectors.toList());
}
filterFruits(fruits, fruit -> fruit.getName().equals("사과"));
filterFruits(fruits, Fruit::isApple);
fun main() {
val fruits = listOf(
Fruit("사과", 1_000),
Fruit("사과", 1_200),
Fruit("사과", 1_200),
Fruit("사과", 1_500),
Fruit("바나나", 3_000),
Fruit("바나나", 3_200),
Fruit("바나나", 2_500),
Fruit("수박", 10_0000)
)
val isApple: (Fruit) -> Boolean = fun(fruit: Fruit): Boolean {
return fruit.name == "사과"
}
val isApple2: (Fruit) -> Boolean = { fruit: Fruit -> fruit.name == "사과 }
isApple(fruits[0])
isApple.invoke(fruits[0])
filterFruits(fruits, isApple)
filterFruits(fruits, fun(fruit: Fruit): Boolean {
return fruit.name == "사과"
})
filterFruits(fruits) { fruit: Fruit -> fruit.name == "사과 } // 마지막 파라미터가 함수인 경우, 소괄호 밖에 람다 사용 가능
filterFruits(fruits) { it.name == "사과" } // 람다를 작성할 때, 람다의 파라미터를 it으로 직접 참조할 수 있다.
}
private fun filterFruits (
fruits: List<Fruit>, filter: (Fruit) -> Boolean
): List<Fruit> {
val results = mutableListOf<Fruit>()
for (fruit in fruits) {
if (filter.invoke(fruit)) {
results.add(fruit)
}
}
return results
}
String targetFruitName = "바나나";
targetFruitName = "수박";
filterFruits(fruits, (fruit) -> targetFruitName.equals(fruit.getName()));
fun readFile(path: String) {
BufferedReader(FileReader(path)).use { reader ->
println(reader.readLine())
}
}
public inline fun <T : Closeable?, R> T.use(block: (T) -> R): R {
val apples = fruits.filter { fruit -> fruit.name == "사과" }
val apples = fruits.filterIndexed { idx, fruit ->
println(idx)
fruit.name == "사과"
}
val applePrices = fruits.filter { fruit -> fruit.name == "사과" }
.map { fruit -> fruit.currentPrice }
val applePrices = fruits.filter { fruit -> fruit.name == "사과 }
.mapIndexed { idx, fruit ->
println(idx)
fruit.currentPrice
}
val values = fruits.filter { fruit -> fruit.name == "사과" }
.mapNotNull { fruit -> fruit.nullOrValue() }
private fun filterFruits(
fruits: List<Fruit>, filter: (Fruit) -> Boolean
): List<Fruit> {
return fruits.filter(filter)
}
val isAllApple = fruits.all { fruit -> fruit.name == "사과" }
val isNoApple = fruits.none { fruit -> fruit.name == "사과" }
val isAnyApple = fruits.none { fruit -> fruit.factoryPrice >= 10_000 }
val fruitCount = fruits.count()
val fruits = fruits.sortedBy { fruit -> fruit.currentPrice }
val fruits = fruits.sortedByDescending { fruit -> fruit.currentPrice }
val distinctFruitNames = fruits.distinctBy { fruit -> fruit.name }
.map { fruit -> fruit.name }
fruits.first()
fruits.firstOrNull()
fruits.last()
fruits.lastOrNull()
val map: Map<String, List<Fruit>> = fruits.groupBy { fruit -> fruit.name }
val map: Map<Long, Fruit> = fruits.associateBy { fruit -> fruit.id }
val map: Map<String, List<Long>> = fruits
.groupBy({ fruit -> fruit.name }, { fruit -> fruit.factoryPrice })
val map: Map<Long, Long> = fruits
.associateBy({ fruit -> fruit.id }, { fruit -> fruit.factoryPrice })
val map: Map<String, List<Fruit>> = fruits.groupBy { fruit -> fruit.name }
.filter { (key, value) -> key == "사과" }
val fruitsInList: List<List<Fruit>> = listOf(
listOf(
Fruit(1L, "사과", 1_000, 1_500),
Fruit(2L, "사과", 1_200, 1_500),
Fruit(3L, "사과", 1_200, 1_500),
Fruit(4L, "사과", 1_500, 1_500),
),
listOf(
Fruit(5L, "바나나", 3_000, 3_200),
Fruit(6L, "바나나", 3_200, 3_200),
Fruit(7L, "바나나", 2_500, 3_200),
),
listOf(
Fruit(8L, "수박", 10_000, 10_000),
)
)
val samePriceFruits = fruitsInList.flatMap { list ->
list.filter { fruit -> fruit.factoryPrice == fruit.currentPrice }
}
data class Fruit(
val id: Long,
val name: String,
val factoryPrice: Long,
val currentPrice: Long,
) {
val isSamePrice: Boolean
get() = factoryPrice == currentPrice
}
val List<Fruit>.samePriceFilter = List<Fruit>
get() = this.filter(Fruit::isSamePrice)
val samePriceFruits = fruitsInList.flatMap { list -> list.samePriceFilter }
fruitsInList.flatten()
참고