변환
map, filter, flatMap을 알아봅니다
변환은(는) CoddyKit의 무료 Scala for Backend Engineering & Functional Programming 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Scala for Backend Engineering & Functional Programming 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Scala for Backend Engineering & Functional Programming 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Transforming collections
Scala collections are immutable by default. Instead of mutating them, you transform them into new collections using methods like map, filter, and flatMap.
object Main {
def main(args: Array[String]): Unit = {
val nums = List(1, 2, 3, 4)
val doubled = nums.map(_ * 2)
println(nums)
println(doubled)
}
}map: transform every element
map applies a function to each element and returns a new collection of the same size. The element type may change.
object Main {
def main(args: Array[String]): Unit = {
val words = List("scala", "rocks")
val lengths = words.map(_.length)
println(lengths)
}
}The underscore shorthand
The underscore _ is shorthand for a single function parameter. _ * 2 means x => x * 2. It keeps simple transformations compact.
object Main {
def main(args: Array[String]): Unit = {
val nums = List(10, 20, 30)
println(nums.map(_ + 1))
println(nums.map(x => x + 1))
}
}filter: keep matching elements
filter keeps only the elements for which the predicate returns true. The result may be smaller than the original.
object Main {
def main(args: Array[String]): Unit = {
val nums = (1 to 10).toList
val evens = nums.filter(_ % 2 == 0)
println(evens)
}
}filterNot: the opposite
filterNot keeps elements where the predicate is false. It is the complement of filter.
object Main {
def main(args: Array[String]): Unit = {
val nums = List(1, 2, 3, 4, 5)
println(nums.filterNot(_ % 2 == 0))
}
}flatMap: map then flatten
flatMap applies a function that returns a collection for each element, then flattens the results into one collection.
object Main {
def main(args: Array[String]): Unit = {
val words = List("ab", "cd")
val chars = words.flatMap(_.toList)
println(chars)
}
}map vs flatMap
If your function returns a collection, map gives you nested collections while flatMap gives you a flat one. Choose based on the shape you want.
object Main {
def main(args: Array[String]): Unit = {
val nums = List(1, 2, 3)
println(nums.map(n => List(n, n)))
println(nums.flatMap(n => List(n, n)))
}
}flatMap with Option
flatMap over a list of Option drops the None values and unwraps the Some values, a handy way to filter and transform at once.
object Main {
def main(args: Array[String]): Unit = {
val raw = List("1", "x", "3", "y")
val parsed = raw.flatMap(_.toIntOption)
println(parsed)
}
}collect: filter and map together
collect takes a partial function: it keeps and transforms only the elements the function is defined for, combining filter and map in one pass.
object Main {
def main(args: Array[String]): Unit = {
val mixed: List[Any] = List(1, "two", 3, "four", 5)
val ints = mixed.collect { case i: Int => i * 10 }
println(ints)
}
}Chaining transformations
Because each method returns a new collection, you can chain them into a readable pipeline. Each step transforms the output of the previous one.
object Main {
def main(args: Array[String]): Unit = {
val result = List(1, 2, 3, 4)
.map(_ + 1)
.filter(_ % 2 == 0)
println(result)
}
}A clean pipeline
Here is a tidy transformation pipeline: filter even numbers, square them, then keep the large ones. Pipelines read like a description of the data flow.
object Main {
def main(args: Array[String]): Unit = {
val result = (1 to 10).toList
.filter(_ % 2 == 0)
.map(x => x * x)
.filter(_ > 10)
println(result)
}
}Quick Check
What does List("ab", "cd").flatMap(_.toList) return?
Recap
You learned the core transformations:
map— transform each element, same sizefilter/filterNot— keep or drop by predicateflatMap— map then flatten nested resultscollect— filter and map with a partial function- Chain them into readable, immutable pipelines
자주 묻는 질문
“변환” 강의는 무료인가요?
네 — “변환” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Scala for Backend Engineering & Functional Programming 강의 전체를 잠금 해제할 수 있습니다. Scala for Backend Engineering & Functional Programming 강의에는 총 4개의 강의가 포함되어 있습니다.
“변환”에서 뭘 배우나요?
map, filter, flatMap을 알아봅니다 브라우저에서 직접 실행하는 실습 코드로 Scala for Backend Engineering & Functional Programming을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Scala for Backend Engineering & Functional Programming을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Scala for Backend Engineering & Functional Programming은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.
“변환” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Scala for Backend Engineering & Functional Programming 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Scala for Backend Engineering & Functional Programming 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.