Skip to content

Instantly share code, notes, and snippets.

@Rohit-554
Created December 25, 2025 13:44
Show Gist options
  • Select an option

  • Save Rohit-554/23b9a1b7da9fdde1f63dcd5289a4d830 to your computer and use it in GitHub Desktop.

Select an option

Save Rohit-554/23b9a1b7da9fdde1f63dcd5289a4d830 to your computer and use it in GitHub Desktop.
package io.jadu
import java.io.File
data class User(
val name: String?,
val email: String?,
val role: String,
val age: Int
)
class Repository {
fun getUser(id: Int): User? {
return when(id) {
1 -> User("Alice", "[email protected]", "admin", 30)
2 -> User("Bob", null, "user", 25)
3 -> User(null, "[email protected]", "guest", 15)
else -> null
}
}
fun getAllUsers(): List<User> {
return listOf(
User("Alice", "[email protected]", "admin", 30),
User("Bob", null, "user", 25),
User("Charlie", "[email protected]", "admin", 35),
User("Dave", "[email protected]", "guest", 12)
)
}
}
fun sendMessage(email: String) {
println(">> Sent email to $email")
}
fun logError(message: String) {
println(">> ERROR: $message")
}
fun executeNullCheckOld(id: Int) {
val repo = Repository()
val user = repo.getUser(id)
if (user != null) {
val email = user.email
if (email != null) {
sendMessage(email)
} else {
logError("Email is missing")
}
} else {
logError("User not found")
}
}
fun executeNullCheckNew(id: Int) {
val repo = Repository()
repo.getUser(id)?.email?.let {
sendMessage(it)
} ?: logError("User or Email missing")
}
fun getRoleDescriptionOld(user: User): String {
if (user.role == "admin") {
return "Has full access"
} else if (user.role == "user") {
return "Has limited access"
} else {
return "Read only"
}
}
fun getRoleDescriptionNew(user: User) = when (user.role) {
"admin" -> "Has full access"
"user" -> "Has limited access"
else -> "Read only"
}
fun processAdminsOld() {
val repo = Repository()
val users = repo.getAllUsers()
val adminNames = ArrayList<String>()
for (u in users) {
if (u.role == "admin" && u.age > 20) {
val name = u.name
if (name != null) {
adminNames.add(name.uppercase())
}
}
}
for (name in adminNames) {
println(name)
}
}
fun processAdminsNew() {
val repo = Repository()
repo.getAllUsers()
.filter { it.role == "admin" && it.age > 20 }
.mapNotNull { it.name?.uppercase() } // A, null, b -> A, B
.forEach { println(it) }
}
fun configureFileOld() {
val file = File("test.txt")
file.setReadable(true)
file.setWritable(true)
file.setExecutable(false)
println("File config done: ${file.name}")
}
fun configureFileNew() {
val file = File("test.txt").apply {
setReadable(true)
setWritable(true)
setExecutable(false)
}
println("File config done: ${file.name}")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment