Created
October 5, 2020 13:06
-
-
Save benjaminkomen/4820b283a7751d81ce41daca0c8a5b0b to your computer and use it in GitHub Desktop.
Solution to Java to Kotlin Conversion Quiz
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.BufferedReader | |
import java.io.File | |
import java.io.FileReader | |
import java.io.IOException | |
//Java to Kotlin Conversion Quizz samples for Java Magazine | |
//Example 1: Statics | |
object MySingleton { | |
private const val state: Int = 42 | |
} | |
//Example 2: Functions / Primitive/Object conversion hell | |
fun convert(value: String): String { | |
return value | |
.map { it.toInt() } | |
.joinToString { Integer.toBinaryString(it) } | |
} | |
val result = convert("Welcome2Java'sPrimitive2ObjectHell") | |
println(result) | |
//Example 3: Nullability | |
var firstFileInParentFolder = File("/tmp") | |
?.parentFile?.listFiles()?.get(0)?.name | |
?: "unknown" | |
//Example 4: Extension methods | |
fun String.printFile() { | |
try { | |
BufferedReader(FileReader(this)).use { br -> | |
var line: String? | |
while (br.readLine().also { line = it } != null) { | |
println(line) | |
} | |
} | |
} catch (e: IOException) { | |
e.printStackTrace() | |
} | |
} | |
"foo.txt".printFile() | |
//Example 5: Collections | |
val characterCount: Map<Char, Int> = listOf("Count", "us", "all") | |
.joinToString().groupingBy { it }.eachCount() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Based on this quiz, some notes: