Skip to content

Instantly share code, notes, and snippets.

@benjaminkomen
Created October 5, 2020 13:06
Show Gist options
  • Save benjaminkomen/4820b283a7751d81ce41daca0c8a5b0b to your computer and use it in GitHub Desktop.
Save benjaminkomen/4820b283a7751d81ce41daca0c8a5b0b to your computer and use it in GitHub Desktop.
Solution to Java to Kotlin Conversion Quiz
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()
@benjaminkomen
Copy link
Author

Based on this quiz, some notes:

  • example 1 was obvious, an object in Kotlin is a singleton class
  • example 2: wasn't clear if the function signature with the converter function as parameter should be kept, I didn't do it because the type differences between Java and Kotlin was a bit annoying
  • example 3: kotlin thinks a File does not return a null value, but I'm not sure
  • example 4: I created an extension method, like the comment suggested, but I'm not sure what the power of Kotlin is here exactly
  • example 5: nice one!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment