Reading files with Kotlin

Before Kotlin BufferedReader br = new BufferedReader(new FileReader(“data.txt”)); try { StringBuilder sb = new StringBuilder(); String line = br.readLine(); while (line != null) { sb.append(line); sb.append(System.lineSeparator()); line = br.readLine(); } String content = sb.toString(); } finally { br.close(); } This is a code sample reading a files content in plain old Java. What a mess…

How to write unit tests in Kotlin

Dependency First you need to add the following dependency to your build.gradle file dependencies { testImplementation ‘org.jetbrains.kotlin:kotlin-test’ As a second step you need to add the task test { useJUnitPlatform() } Implementation When you are familiar with JUnit you may recognized the @Test annotation. Assertions work pretty much the same. You can choose from a…

Kotlin Tutorial

This is the overview page for my little Kotlin tutorial Learning Kotlin Part 1 – print Learning Kotlin Part 2 – arrays Learning Kotlin Part 3 – ranges Learning Kotlin Part 4 – conditionals Learning Kotlin Part 5 – loops Learning Kotlin Part 6 – functions Learning Kotlin Part 7 – multiple return values Reading…

How to use Snackbars

A Snackbar is a replacement for Toasts in Android. Dependency implementation ‘com.google.android.material:material:1.4.0’ Layout A snackbar must be tied to a coordinator layout. If you use fragments the standard layout is FrameLayout which can be directly swapped with: <androidx.coordinatorlayout.widget.CoordinatorLayout Snackbar val snackbar = Snackbar.make( binding.root, “No internet connection! Please enable WiFi or Mobile Data”, Snackbar.LENGTH_INDEFINITE )…

Logging in Android

Logging brings some light into the darkness of your code. If you are new to logging please have a look at Log4j2 for Kotlin Import import android.util.Log Tag class MainActivity : AppCompatActivity() { companion object { const val TAG = “MainActivity” } Log statement override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) Log.d(TAG, “onCreate”) } Logcat Further…

Classes in Kotlin – Part 2

In Part 1 we dealt with the simplest form of initialization with the primary constructor: class Planet( val diameter: Int, val distanceToSun: Double, val mass: Double ) But wait: there is more: Init block The primary constructor cannot contain any code so init block for the rescue: class Planet( val diameter: Int, val distanceToSun: Double,…

Classes in Kotlin – Part 1

Why is there a car in the picture? – Because it has class! Jokes aside, classes are still the building blocks of modern object oriented software design. And of course as the new kid on the block Kotlin has it’s own take on this subject. Declaration Let’s look at the most basic class declaration: class…