🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
The fold function in Kotlin is used to accumulate a value by applying a binary operation from left to right to the characters in a string, starting with an initial value. This function belongs to the CharSequence class in the Kotlin standard library and is useful for performing reductions such as summing values, concatenating characters, or combining elements in a specific way while starting with an initial value.
Table of Contents
- Introduction
foldFunction Syntax- Understanding
fold - Examples
- Basic Usage
- Summing ASCII Values
- Concatenating Characters with an Initial Value
- Real-World Use Case
- Conclusion
Introduction
The fold function processes each character in a string by applying a binary operation that combines the current accumulated value with the next character, starting with an initial value. This is useful for reducing the string to a single value based on a specific operation, with the ability to start from an initial value.
fold Function Syntax
The syntax for the fold function is as follows:
inline fun <R> CharSequence.fold(initial: R, operation: (acc: R, Char) -> R): R
Parameters:
initial: The initial value to start the accumulation.operation: A lambda function that takes the current accumulated value (acc) and the next character, and returns a new accumulated value.
Returns:
- The final accumulated value after applying the binary operation to all characters in the string.
Understanding fold
The fold function starts with the initial value as the accumulated value and applies the operation function to combine it with each subsequent character. The result of each operation becomes the new accumulated value for the next iteration.
Examples
Basic Usage
To demonstrate the basic usage of fold, we will concatenate all characters in a string starting with an initial value.
Example
fun main() {
val text = "Kotlin"
val result = text.fold("Start: ") { acc, char -> acc + char }
println("Original text: $text")
println("Concatenated result: $result")
}
Output:
Original text: Kotlin
Concatenated result: Start: Kotlin
Summing ASCII Values
This example shows how to use fold to sum the ASCII values of all characters in a string, starting with an initial value of 0.
Example
fun main() {
val text = "Kotlin"
val sumAsciiValues = text.fold(0) { acc, char -> acc + char.toInt() }
println("Original text: $text")
println("Sum of ASCII values: $sumAsciiValues")
}
Output:
Original text: Kotlin
Sum of ASCII values: 620
Concatenating Characters with an Initial Value
This example demonstrates how to concatenate characters in a specific way using fold, starting with an initial string.
Example
fun main() {
val text = "Kotlin"
val reversed = text.fold("Reversed: ") { acc, char -> char + acc }
println("Original text: $text")
println("Reversed text using fold: $reversed")
}
Output:
Original text: Kotlin
Reversed text using fold: n: nilotK
Real-World Use Case
Building a CSV String
In real-world applications, the fold function can be used to build a CSV string from the characters of a string, starting with an initial header.
Example
fun main() {
val text = "Kotlin"
val csvString = text.fold("Char, ASCII\n") { acc, char -> acc + "$char, ${char.toInt()}\n" }
println("CSV representation:\n$csvString")
}
Output:
CSV representation:
Char, ASCII
K, 75
o, 111
t, 116
l, 108
i, 105
n, 110
Conclusion
The fold function in Kotlin's CharSequence class is a powerful method for accumulating values by applying a binary operation to each character in a string, starting with an initial value. It provides a way to reduce a string to a single value based on specific operations, making it useful for various applications such as summing values, concatenating characters, and building complex strings.
By understanding and using this function, you can effectively manage reduction operations in your Kotlin applications.
My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:
Build REST APIs with Spring Boot 4, Spring Security 7, and JWT
[NEW] Learn Apache Maven with IntelliJ IDEA and Java 25
ChatGPT + Generative AI + Prompt Engineering for Beginners
Spring 7 and Spring Boot 4 for Beginners (Includes 8 Projects)
Available in Udemy for Business
Building Real-Time REST APIs with Spring Boot - Blog App
Available in Udemy for Business
Building Microservices with Spring Boot and Spring Cloud
Available in Udemy for Business
Java Full-Stack Developer Course with Spring Boot and React JS
Available in Udemy for Business
Build 5 Spring Boot Projects with Java: Line-by-Line Coding
Testing Spring Boot Application with JUnit and Mockito
Available in Udemy for Business
Spring Boot Thymeleaf Real-Time Web Application - Blog App
Available in Udemy for Business
Master Spring Data JPA with Hibernate
Available in Udemy for Business
Spring Boot + Apache Kafka Course - The Practical Guide
Available in Udemy for Business
Comments
Post a Comment
Leave Comment