Category: Tutorial

Why you should start contributing to StackOverflow

Why you should start contributing to StackOverflow

A little History

A few years back, when I started getting into programming, I googled a lot of the problems I was facing during the day and mostly found my answers on StackOverflow. The place that every programmer is kind of dependent on. I still face problems and I still find my answers on StackOverflow. Something has changed, though. I don’t only consume content on the website but also contribute to it. Until May 2017,Β I didn’t even have an account on StackOverflow. At this time, I was getting interested in knowing how it’s like to answer questions instead of just reading them. I enjoyed helping others to solve their Kotlin-related problems ever since I started learning the Kotlin programming language. This was my initial motivation for creating an account and contributing to StackOverflow.

The Kotlin Gold Badge

A few weeks back, after 10 months of answering about 400 questions, I was awarded the golden Kotlin badge, which means that I spend quite some time on the platform already. I was always motivated to receive the badge since only three other people got it by then. You can become kind of addicted to answering actually… πŸ˜‰

stackoverflow-kotlin-gold-s1m0nw1

Lessons Learned

Teaching improves yourself

When I began with contributing to StackOverflow, I had to realize that it can be quite hard to give answers on the fly. It’s not that easy. You most often need to think about the way of looking at the problem from the questioner’s point of view. Regularly, you’ll find yourself researching for answers by studying the documentation, forums and other resources. Most questions also require you to solve the presented problem in your own IDE before coming up with a solution. It can be really time-consuming if you really try to understand other people’s problems. Nevertheless, the whole effort was totally worth it since I learned so many things about the Kotlin language itself and also about problem-solving in general. You don’t always know the answer to up-showing questions immediately and therefore have to put in some thoughts. This is always helpful and very valuable.

Give something back

What I also learned during that time is the fact that you shouldn’t always just take. In the case of StackOverflow, it’s almost disgraceful if you only read posts without telling the authors that their work helped you. I did the same for many years myself. You don’t need to feel bad about it but please take into consideration how much effort has been put into the questions and answers posted there. It really isn’t that hard to actually vote on these posts. If you don’t do this yet, create an account right away and give something back to the people you learn from.

Why you should start contributing

In my opinion, contributing to StackOverflow is a good thing for many reasons. It’s obvious that you’ll learn something from teaching and help others inescapably. Whatever topic you choose to participate in, you’ll be better at it afterward. More importantly, you’ll learn to value the contributions of the fellow answerers. You’ll recognize that it sucks if you don’t get up-voted by the people that consume your knowledge for free and you’ll probably never leave good answers (to the problems you searched for) without voting for them anymore. Even if you don’t want to answer questions, voting should be the least you should start with. If you’re willing to become an answerer though, I’d recommend choosing a niche topic like I did with Kotlin (which still needs expert contributors!). Entering tags like Java, on the other hand, is much more difficult because so many people are already involved in it.

Interestingly, I started a quick poll on Twitter which confirmed my assumptions: Most developers consume but don’t offer knowledge on StackOverflow.

twitter-stackoverflow-poll-s1m0nw1

I hope this makes sense and provokes a few readers to follow my advice.

EDIT:

I have to admit that I have experienced the StackOverflow community for just a short period of time and in the niche area of Kotlin, a language that still isn’t mainstream. I understand that StackOverflow is not just good and there are reasons you can criticise it for. If, after reading this article, you’re willing to learn from StackOverflow users, that have experienced the bad habits of the website, you should definitely read this post: My Love-Hate Relationship with StackOverflow.

Please follow and like this Blog πŸ™‚
Publish Kotlin Library on Bintray using Gradle Kotlin DSL and Travis CI

Publish Kotlin Library on Bintray using Gradle Kotlin DSL and Travis CI

Distribute a Library on Bintray using Gradle Kotlin DSL

In my latest blog post, published a few weeks back, I informed about the usage of the Gradle Kotlin DSL and how it helps with describing build scripts. In another earlier post, I introduced a small library that can be utilized for simplifying the creation of TLS/SSL sockets using a custom Kotlin DSL: SeKurity.

In this post, we’ll investigate how such a library can be made available to others that actually want to make use of it inside other projects. Ultimately, it should be possible to list the SeKurity library as a simple dependency in a build script like Maven or Gradle. Since the library itself is already backed by Gradle, I’ll show a way of publishing the resulting artifacts at the end of that build.

Where to publish?

In order to make a library available to anybody else, it needs to be published to a publicly accessible e.g. Maven repository like the famous Maven Central. Unless you’re absolutely certain about the quality of your library, it’s recommended to share it on custom repositories rather than THE central one directly as you’ll kinda lose control of it once it’s out there. One alternative is called Bintray and it will also be used in the present article. After creating an account or simply signing in with your GitHub, Google or Twitter account, you can create your own repositories there.

Automating the Build

Before enabling our build to publish the built artifacts, the process should be automated in a CI tool like Travis CI, which interacts nicely with GitHub. To make it work, it must be enabled in the GitHub repo settings by adding it as a service (see Settings -> Integrations & services). Travis expects the repository to incorporate a .travis.yml configuration that tells it what to do. For a simple Java/Kotlin project using Gradle, the following will be sufficient:

language: java

before_install:
- chmod +x gradlew

script: ./gradlew clean bintrayUpload -PbintrayUser=$BINTRAY_USER -PbintrayApiKey=$BINTRAY_KEY

It’s normally not necessary to specify the script command explicitly as long as you’re using the default instructions. In the shown case, Gradle runs the bintrayUpload task, which we will learn about later. The used properties $BINTRAY_USER and $BINTRAY_KEY contain private data and are therefore securely stored in Travis directly. When the build is run, Travis takes care of replacing them.
You can finally enable the repository in Travis and it will start a build on every push immediately. For further information on Travis, the documentation is highly recommended.

The Gradle Build

As shown earlier, the bintrayUpload Gradle task gets invoked in the build. Where does it come from? Let’s have a look at the relevant parts of the gradle.build.kts file.

The Plugins

plugins {
    kotlin("jvm") version "1.2.30"
    id("com.github.johnrengelman.shadow") version "2.0.2"
    `maven-publish`
    id("com.jfrog.bintray") version "1.8.0"
}
  • The shadow plugin is used because we need the library to be bundled with all its dependencies in order to avoid classpath conflicts.
  • The maven-publish plugin helps with creating the relevant artifact and a relevant pom.xml file that will also be published.
  • The bintray plugin does all the heavy work at the end of the build. It refers to the maven-publish result and pushes the artifacts to Bintray.

Plugin Configuration

The build file also adds custom configurations for all previously shown plugins as shown next:

I Shadow

val artifactID = "sekurity"

val shadowJar: ShadowJar by tasks
shadowJar.apply {
     baseName = artifactID
     classifier = null
}

The shadow plugin uses the project’s name as the artifact’s baseName and the “all” qualifier by default, which is overridden here.

II Maven-Publish

fun MavenPom.addDependencies() = withXml {
    asNode().appendNode("dependencies").let { depNode ->
        configurations.compile.allDependencies.forEach {
            depNode.appendNode("dependency").apply {
                appendNode("groupId", it.group)
                appendNode("artifactId", it.name)
                appendNode("version", it.version)
            }
        }
    }
}

val publicationName = "tlslib"
publishing {
    publications.invoke {
        publicationName(MavenPublication::class) {
            artifactId = artifactID
            artifact(shadowJar)
            pom.addDependencies()
        }
    }
}

This one is a bit tricky. We reuse the result of shadow and add it to the publication which will be published under the artifactId that corresponds to the JAR’s baseName. By default, the generated POM does not list the library dependencies, which is done by mapping each compile dependency to a valid dependency XML node.

III Bintray

fun findProperty(s: String) = project.findProperty(s) as String?

bintray {
    user = findProperty("bintrayUser")
    key = findProperty("bintrayApiKey")
    publish = true
    setPublications(publicationName)
    pkg(delegateClosureOf {
        repo = "SeKurity"
        name = "SeKurity"
        userOrg = "simon-wirtz"
        vcsUrl = "https://github.com/s1monw1/TlsLibrary"
        setLabels("kotlin")
        setLicenses("MIT")
    })
}

The bintray plugin is most important since it takes care of actually uploading the generated artifacts to Bintray itself. The user and key are obtained from the Gradle project properties, which are passed by Travis later on as already shown earlier. By referring to the publication created in maven-publish, all artifacts will be uploaded as specified. The pkg block describes the library’s attributes and where, i.e. to what repository, the publishing happens.

The Result

All these blocks merged result in a pretty nice Gradle build script, which can be observed in this Gist and also the SeKurity repository itself. The resulting artifact is made available here: https://bintray.com/simon-wirtz/SeKurity

Referring to the published Library

Now that the library is being uploaded to Bintray, it can be listed as a dependency in arbitrary build files. If we have another Gradle-backed project, we first need to add the relevant repository to the list of repositories:

repositories {
    mavenCentral()
    jcenter()

    maven {
        setUrl("https://simon-wirtz.bintray.com/SeKurity")
    }
}

After that, the library can be added as a simple compile dependency like this:

dependencies {
    compile(kotlin("stdlib-jre8", kotlinVersion))
//...others...

    compile("de.swirtz:sekurity:0.0.1")

}

Recap

As shown, Gradle plugins can be used for setting up a proper build that publishes a custom library to Bintray easily. In order to automate the whole process, CI tools like Travis can be used for executing the build whenever a new change has been made.

I hope the little tutorial helps with your build as well! If you like, have a look at my Twitter account and follow if you’re interested in more Kotlin stuff πŸ™‚ Thanks a lot.

Please follow and like this Blog πŸ™‚
Kotlin Quick Reference – Getting Started with Kotlin

Kotlin Quick Reference – Getting Started with Kotlin

Introduction

Disclaimer: This reference has originally been published as a DZone Refcard.

Kotlin has become one of the most popular JVM languages in the past few months. One special reason is that it experienced a lot of attention in the Android community after Google made Kotlin an official language for Android development. Kotlin is being developed by JetBrains, who are responsible for the most famous IDEs out there, most notably IntelliJ IDEA. Nevertheless, it’s an open source language, which can be found on GitHub.

The language is said to be very concise, safe in terms of error frequency, interoperable with Java and also offers many features that enable functional programming, writing type-safe DSLs and much more. Beside the JVM, Kotlin can compile for most Android versions, down to machine code using LLVM and can also be transpiled to JavaScript.
Kotlin has already been adopted in many popular frameworks and tools such as Spring and Gradle. It continues to gain traction in multiple domains, and there has never been a better time to get started with Kotlin.

Where to Start Coding

When you want to start writing your first Kotlin code there are quite a few ways to do that. Apparently, the recommended way is to work with IntelliJ IDEA, which offers the best support. As an alternative, one could also start with the command line or use JetBrains’ Kotlin web IDE to do some Kotlin Koans. Whichever way you prefer, corresponding tutorials can be found here: kotlinlang.org/docs/tutorials/.

Basic Syntax

Kotlin was inspired by many modern programming languages like C#, Groovy, Scala and also Java. Even more, Kotlin can be seen as an extension to the Java language, making it better by adding functionality to existing standard classes (e.g. String, List) and of course by providing great features, which are in large part enabled by applying compiler-supported techniques. As in Java, Kotlin programs are entered via a main method, such as the following:

fun main(args: Array): Unit {
    val inserted = "Kotlin"
    println("Let's get started with $inserted")
}

What we can see in this snippet is:

  • Functions are initiated by the keyword fun, followed by a name
  • Parameters and also variables in Kotlin are declared by defining a name and a type, both separated by a colon as you can see in args: Array
  • The return type of the main is Unit, also prefaced by a colon. In case of a Unit return, which corresponds to Java’s void, the compiler does not require you to explicitly define the return type, so the part : Unit could be omitted
  • Kotlin does not require you to use semicolons for separating statements (in most cases)
  • Type inference is supported in many situations as shown with val inserted, which also could be declared with an explicit type as val inserted: String
  • String templates can be used, which means that it’s possible to include variables and even expressions in Strings directly using $varname or ${statement} syntax
  • main is declared without a wrapping class around it. Functions and variables in Kotlin may be declared at “top-level”, i.e directly inside a package
  • No visibility modifier is used here. Functions, classes, variables etc. are public by default. When different visibility is needed, choose from:
KeywordEffect on Top-Level declarations [1]Effect on Class Members
publicvisible everywherevisible everywhere if class is accessible
privatevisible inside the file onlyvisible inside the class only
protectedvisible in class and subclasses
internalvisible inside the same module [2]visible in the same module, if class is accessible

1: Functions, properties and classes, objects and interfaces can be declared on the “top-level”
2: A module is a set of Kotlin files compiled together: an IntelliJ IDEA module, a Maven project, a Gradle source set

  • Variables defined as val cannot be re-assigned, i.e. are read-only. Alternatively, if mutability is inevitable, var can be utilized, as shown in the next example:
var mutableVar = StringBuilder("first")
mutableVar = StringBuilder("second")
  • Constructor is invoked without the new keyword, which is omitted from kotlin

Control Flow: Conditions

In Kotlin you can make use of if, when, for and while for controlling the behavior of your code. Let’s look at conditions first.

If-Statement

val min: Int
if (x < y) {
    min = x
} else {
    min = y
}

It’s important to know, that many statements in Kotlin can also be used as expressions, which for instance makes a ternary operator obsolete and apparently shortens the code in most cases:

val min = if (x < y) x else y 

When-Statement

A when statement is very similar to switch operators and could, in theory, easily replace if-statements as they are much more powerful.

val y = when (x) {
    0 -> "is zero"
    1 -> "is one"
    2, 3 -> "two or three"
    is Int -> "is Int"
    is Double -> "is Double"
    in 0..100 -> "between 0 and 100"
    else -> "else block"
}

In a when statement, which can also be used as an expression, all branches are tried to match the input until one condition is satisfied. If no branch matches, the else is executed. As shown in the snippet, when branch conditions can be values, types, ranges and more.

Control Flow: Loops

For-Loop

In Kotlin, there’s no conventional for-loop, as you know it from C or Java. Instead, foreach loops are the default.

for (c in "charSequence") {
    println(c)
}

In many cases, looping with an index is necessary, which can easily be achieved with the indices property that is defined for arrays, lists and also CharSequences for example.

for (i in "charSequence".indices) {
    println("charSequence"[i])
}

Another way of iterating with indices is possible by using withIndix().

for ((i,c) in "charSequence".withIndex()) {
    println("$i: $c")
}

Last but not least, Kotlin has ranges, which can also be utilized for indexed iterations as the following shows:

(0 .. "charSequence".length-1).forEach {
    print("charSequence"[it])
}

The range in this example is expressed with the common .. syntax. To create a range which does not include the end element (s.length), the until function is used: (0 until s.length).

While-Loop

Constructs with while or do-while loops are straight-forward, all works as known from other common languages.

Basic Types

In Kotlin everything looks like an object to the user, even primitive types. This means, member functions can be called on every type, although some will be represented as JVM primitives at runtime.

Numbers

The default number types are: Double, Float, Long, Int, Short, Byte
* Underscores can be used to make large numbers more readable: val million = 1_000_000
* Number types offer conversion methods like toByte(): Byte, toInt(): Int , toLong(): Long
* Characters are no number type in Kotlin

Chars

A Char represents characters and cannot be treated as a number.
* They are declared within single quotes, e.g. '42'
* An explicit conversion from a Char to an Int can be accomplished with the toInt() method

Booleans

Booleans can have the two common values true and false
* They can be operated on with: ||, && and !

Strings

Strings are immutable sequences of characters.
* They offer an index operator [] for accessing characters at specified positions
* A string literal in Kotlin looks like "Hello World" or """Hello World with "another String" in it"""
* The latter is called raw string that can contain any character without needing to escape special symbols
* Strings in Kotlin may contain template expressions

Arrays

An array is represented by the class Array, which offers very useful methods to the client.
* Values can be obtained via get(index) or [index]
* Values can be set via set(index, value) or [index]=value
* Arrays are invariant, i.e. an Array cannot be assigned to a variable of type Array
* Special types for arrays of primitive types exist as IntArray or ShortArray for instance. Using those will reduce the boxing overhead.

Classes

A simple class can be declared like in this snippet:

class Person constructor(name: String) {}

The primary constructor is part of the class header, secondary constructors can be added in the class body. In the shown case, the constructor keyword could also be omitted, since it’s only mandatory if you want to add annotations or visibility modifiers (default: public).
Constructor parameters such as name can be used during the initialization of an object of this class. For this purpose, an init block would be necessary, because primary constructors can’t contain code directly. Constructor arguments can also be used in property initializers that are declared in the class body, as shown here.

class Person(name: String, age: Int) {
    init {
        println("new Person $name will be born.")
    }
    val ageProp = age
}

As mentioned, Kotlin classes can contain properties, which are accessed by simply calling obj.propertyName to get a property’s value and obj.propertyName = "newValue" to modify the value of a mutable (var) property. Declaring properties for classes can also be done in the primary constructor directly, which makes the code even more concise. Like in all methods, Kotlin supports default parameters for parameters, set with “=“.

class Person(val name: String, val age: Int = 50)

Same as with local variables, instead of val, a property can be declared mutable using var instead. Note that you don’t have to write an empty class body if no content is defined.

Special Classes

Besides ordinary classes, Kotlin knows a few special class declarations, which are worth knowing. The following will give a quick overview.

TypeExplanation
data classAdds standard functionality for toString, equals, hashCode etc.
sealed classRestricts class hierarchies to a set of subtypes. Useful with when
Nested classClasses can be created in other classes, also known as “inner class”
enum classCollect constants that can contain logic
object declarationsUsed to create Singletons of a type

Of course, Kotlin also supports inheritance through interfaces and abstract classes.

Function Types and Lambdas

In order to be able to understand idiomatic Kotlin code, it’s essential to recognize how function types and especially lambdas look like. Just as you can declare variables of type Int or String, it’s also possible to declare variables of function types, e.g. (String) -> Boolean.

val myFunction: (String) -> Boolean = { s -> s.length > 3 }
myFunction("HelloWorld")

The variable is declared as a function type that takes a String argument and returns a Boolean. The method itself is defined as a lambda enclosed in curly braces. In the shown lambda, the String parameter is declared and named before the -> symbol, whereas the body follows after it.

Lambda Special Syntax

The language designers decided on some special lambda features, which make the usage even more powerful.

  1. it: implicit name of single parameters

In many cases, lambdas are used with single parameters like in the previous example. In such situations, you don’t have to give the parameter an explicit name. Instead, the implicit name it can be used.

val myFunction: (String) -> Boolean = { it.length > 3 }
myFunction("HelloWorld")
  1. For unused parameters, use _

In some cases, it might be unnecessary to make use of every possible available parameter in a lambda. The compiler warns the developer about such unused variables, which can be avoided by naming it with an underscore.

val myFunction: (String, Int) -> Boolean = { s, _ -> s.length > 3 }
myFunction("HelloWorld", 42)

Higher-Order Functions

If a function takes another function as an argument or returns another function as its result, it’s called a higher-order function. Such functions are essential in Kotlin as many library functions rely on this concept. Let’s see an example.

fun main(args: Array) {
    myHigherOrderFun(2, { it.length > 2 })
}

fun myHigherOrderFun(iterations: Int, test: (String) -> Boolean){
    (0 until iterations).forEach {
        println("$it: ${test("myTestString")}")
    }
}

The function myHigherOrderFun defines two parameters, one of which is another function test. The function takes test and applies a String to it multiple times depending on what the first argument iterations is. By the way, the example uses a range to imitate an indexed for loop here.

The shown main function demonstrates the usage of a higher-order function by calling it with an anonymous function. The syntax looks a bit messy, which is why the language designers decided on a very important convention: If a lambda is the last argument to a function, it can be placed after the closing parentheses or, if it’s the only argument, the parentheses can be omitted completely like shown with forEach above. The following snippet demonstrates this convention applied to an invocation of myHigherOrderFun.

//Lambda after closing parentheses
myHigherOrderFun(2) {
    it.length>2
}

Top Features

There are some features in Kotlin, everybody should be familiar with. These are essential for many libraries, standard functions and also advanced features like Domain Specific Language support.

Null-Safety

The type system differentiates between nullable and non-null types. By default, a class like String cannot reference null, which raises the attention for null-related problems. As opposed to String, the type String? can hold null. This does not make a big difference on its own. Therefore, working with nullable types implies having to handle nullable values in a special way.

var b: String? = "couldBeNull"
b = null //okay

// 1. Access directly: does not compile, could throw NPE
// val len = b.length

//2. Use safe-operator
val len = b?.length

//3. Check nullability before accessing
if(b != null){
    b.length
}

It’s possible to check whether a variable is not null before accessing it. In such cases, the compiler permits the usage without special safety measures. Alternatively, b?.length expresses: call length on b if it’s not null, otherwise the expression returns null. The return is of type Int? because null may be returned. Chaining such calls is possible, which is very useful. Other operators used with nullable types are shown in the following overview.

| Operator | Use case | Example
| ——————- | —————————— | —————- |
| !! | Ignore warnings of compiler and overcome null checks. Use cautiously only. | val x: String? = "nullable"
x!!.length |
| ?: | The elvis operator is used to give an alternative for null results. | val x: String? = "nullable"
val len: Int = b?.length ?: 0
| as? | A safe cast tries to cast a variable in a type and results in null if the cast is not possible. | val i: Int? = s as? Int

Extensions

Another essential feature of Kotlin is extensions. An extension is used to extend a class with new functionality without having to inherit from that class. Extensions can have the form of properties and functions. The Kotlin standard library contains a lot of such extensions, like the following defined on String:

public fun String.substring(range: IntRange): String = substring(range.start, range.endInclusive + 1)

//usage
"myString".substring(0..3)

In this example String is the receiver of the defined substring(range: IntRange) function. An extension function can use visible members of its receiver without additional qualifiers since this refers to the receiver. In the snippet, String‘s standard method substring(startIndex: Int, endIndex: Int) is called in that way. The extension is called on a String as if it was a regular method.

It’s also possible to extend a class with properties. For example, Int can be extended with a property that represents its version of BigDecimal. This might be useful if otherwise, the constructor of BigDecimal had to be used many times.

val Int.bd
get() = BigDecimal(this)

val bd: BigDecimal = 5.bd

Extensions are mostly defined on top-level and can be used in other files after they have been imported explicitly.

Lambda with Receiver

Higher-order functions can be even more powerful if used with “lambdas with receiver”. It’s possible to call function literals with a specific receiver object, similar to the extension functions. As a result, members of the receiver can directly be accessed inside the lambda without having to use additional qualifiers. This feature is the foundation for Kotlin’s fantastic support for writing Type-Safe Builders, also known as Domain Specific Languages.

fun T.apply(block: T.() -> Unit): T {
    block()
    return this
}

This snippet shows a slightly simplified version of the apply function, which is part of Kotlin’s standard library. It’s an extension function on the generic type T, thus can be used with any object. The function takes a function literal with T as its receiver and executes the block before this (the receiver of apply) is being returned.

data class GuiContainer(var width: Int = 0, var height: Int = 0, var background: String = "red") {
    fun printMe() = println(this)
}

fun main(args: Array) {
    val container = GuiContainer().apply {
        width = 10
        height = 20
        background = "blueish"
        printMe()
    }
}

In this example, the data class GuiContainer is created with default parameters and then the apply method is called on it. It’s possible to set mutable properties and call methods of the receiver GuiContainer like shown with the invocation of printMe() in the end. Since apply returns the receiver after it completes, it can directly be assigned to a variable.

Idiomatic Kotlin

Kotlin tries to encourage particular coding idioms to be used. These are partially listed in the documentation and also in some community driven articles. The following will present some of these idioms by example.

  1. Use when as an expression if possible
fun analyzeType(obj: Any) =
    when(obj){
        is String -> "is String"
        else -> "no String"
    }
  1. Use elvis operator with throw and return to handle nullable values

class Person(val name: String?, val age: Int?) fun process(person: Person) { val pName = person.name ?: throw IllegalArgumentException("Name must be provided.") println("processing $pName") val pAge = person.age ?: return println("$pName is $pAge years old") }
  1. Make use of range checks
fun inLatinAlphabet(char: Char) = char in 'A'..'Z'
  1. Prefer default parameters to function overloads
fun greet(person: Person, printAge: Boolean = false) {
    println("Hello ${person.name}")
    if (printAge)
        println("${person.name} is ${person.age} years old")
}
  1. Use type aliases for function types
typealias StringPredicate = (String) -> Boolean

val pred: StringPredicate = {it.length > 3}
  1. Use data classes for multiple return values
data class Multi(val s: String, val i: Int)

fun foo() = Multi("one", 1)

fun main(args: Array){
    val (name, num) = foo()
}
  1. Prefer extension functions to utility-style functions
fun Person.greet(printAge: Boolean = false) {
    println("Hello $name")
    if (printAge)
        println("$name is $age years old")
}
  1. Use apply for object initialization
data class GuiContainer(var width: Int = 0, var height: Int = 0, var background: String = "red") {
    fun printMe() = println(this)
}

fun main(args: Array) {
    val container = GuiContainer().apply {
        width = 10
        height = 20
        background = "blueish"
        printMe()
    }
}
  1. Use compareBy for complex comparisons
fun sort(persons: List): List =
    persons.sortedWith(compareBy(Person::name, Person::age))
  1. Use mapNotNull to combine map and filter for non-null values
fun getPersonNames(persons: List): List =
    persons.mapNotNull { it.name }
  1. Use object to apply Singleton pattern
object PersonRepository{
    fun save(p: Person){}
//...
}

//usage
val p = Person("Paul", 40)
PersonRepository.save(p)
  1. Do not make use of !!
//Do not use !!, there's always a better solution
person!!.address!!.street!!.length
  1. Prefer read-only data structures
//Whenever possible, do not use mutable Data Structures

val mutableList: MutableList = mutableListOf(1, 2, 3)
mutableList[0] = 0

val readOnly: List = listOf(1, 2, 3)
readOnly[0] = 0 // Does not compile
  1. Use let to execute code if receiver is not null
fun letPerson(p: Person?) {
    p?.let {
        println("Person is not null")
    }
}

Resources

Language References:
Official Reference Documentation: https://kotlinlang.org/docs/reference/
GitHub repository: https://github.com/JetBrains/kotlin
Collection of Tools and Frameworks: https://kotlin.link
Operators and Keywords Overview: https://kotlinlang.org/docs/reference/keyword-reference.html

Community:
Slack: https://kotlinlang.slack.com
Twitter: https://twitter.com/kotlin
Newsletter: http://kotlinweekly.net
Discussion: https://discuss.kotlinlang.org

Blogs:
JetBrains: https://blog.jetbrains.com/kotlin/
Simon Wirtz: https://kotlinexpertise.com

Misc:
Kotlin in Action Book: Kotlin in Action
Books: https://kotlinlang.org/docs/books.html
Online IDE: https://try.kotlinlang.org

Please follow and like this Blog πŸ™‚
The Power of Gradle Kotlin DSL

The Power of Gradle Kotlin DSL

-The following is based on Gradle 4.3.1-

A few weeks ago I started migrating most of my Groovy-based gradle.build scripts to Kotlin-backed gradle.build.kts scripts using the Kotlin DSL. Why would I do that? Kotlin is my language of choice and I love the idea of using a single language to do all my work. I never learned programming with Groovy and only know the bloody basics, which always makes me think: “This can’t be the best way to do things…”. Kotlin, on the other hand, is a language I use on a daily basis and therefore I know how to use the language appropriately. Additionally, Kotlin is a statically-typed language, whereas Groovy isn’t. IDEs are having hard times offering code completion and error detection at compile time when a Groovy build script is being edited. As for the Kotlin DSL, this isn’t true. Especially IntelliJ knows how to help us with Kotlin development, even in gradle.build.kts files. All these reasons made me take a deeper look at the new style Gradle offers.

Minor Impediments

It can sometimes be a bit tedious to rewrite your gradle.build into gradle.build.kts files, especially in the IDE with all its caches malfunctioning during that process. I often had to reopen my project or even reimport it before IntelliJ understood what was going on. It also often helps to use “Refresh all Gradle projects” button in the Gradle view.

Let’s take a look

The following snippet shows the first part of a working example. It was taken from one of my projects, which is a Kotlin web application based on the Vert.x toolkit. Learn more about the technology in this post I wrote earlier.

The script first defines a few global variables, mostly containing version numbers, which are used throughout the build file. Next, we can observe the plugins block that simply defines a few plugins used for the build. Most importantly, the Kotlin Gradle plugin for JVM applications is included, which we can do with the DSL-specific function kotlin(module: String), that takes its module argument and appends it to "org.jetbrains.kotlin.", which then is put into the id(plugin: String) method, the default api for applying plugins. Last but not least, we can see the listing of dependencies, which again provides a kotlin convenience method we can use to reduce redundant declarations. A similar approach can be seen with the definition of the io.vertx dependencies. In order to only once write the "io.vertx.vertx" String, which is part of every single Vert.x dependency, it’s used as a receiver of let. A first example of real idiomatic code within the build script.

//imports

//taken from the `plugins` defined later in the file
val kotlinVersion = plugins.getPlugin(KotlinPluginWrapper::class.java).kotlinPluginVersion
val kotlinCoroutinesVersion = "0.19.3"

val vertxVersion = "3.5.0" //
val nexusRepo = "http://x.x.x.x:8080/nexus/content/repositories/releases"

plugins {
    kotlin("jvm").version("1.2.0")
    application
    java
    `maven-publish`
}

dependencies {
    compile(kotlin("stdlib", kotlinVersion))
    compile(kotlin("reflect", kotlinVersion))
    compile("org.jetbrains.kotlinx:kotlinx-coroutines-core:$kotlinCoroutinesVersion")

    "io.vertx:vertx".let { v ->
        compile("$v-lang-kotlin:$vertxVersion")
        compile("$v-lang-kotlin-coroutines:$vertxVersion")
        compile("$v-web:$vertxVersion")
        compile("$v-mongo-client:$vertxVersion")
        compile("$v-health-check:$vertxVersion")
        compile("$v-web-templ-thymeleaf:$vertxVersion")
    }

    compile("org.slf4j:slf4j-api:1.7.14")
    compile("ch.qos.logback:logback-classic:1.1.3")
    compile("com.fasterxml.jackson.module:jackson-module-kotlin:2.9.0.pr3")

    testCompile(kotlin("test", kotlinVersion))
    testCompile(kotlin("test-junit", kotlinVersion))
    testCompile("io.vertx:vertx-unit:$vertxVersion")
    testCompile("org.mockito:mockito-core:2.6.2")
    testCompile("junit:junit:4.11")
}

// Part 2
}

The second part of the example project starts with defining repositories, which are used to find dependencies and plugins declared earlier. Again, we see an example of simplifying the code with the help of using the language: The custom Maven repositories are defined using the functional method forEach, and thus shortens the boilerplate. After that, the plugins are being configured, which for instance is necessary for enabling coroutine support or defining the application properties. Finally, we can observe a sequence of task configurations that control the behavior of single build steps, e.g. tests.

// ...Part 1

repositories {
    mavenCentral()
    jcenter()
    listOf("https://www.seasar.org/maven/maven2/",
            "https://plugins.gradle.org/m2/",
            nexusRepo).forEach {
        maven { url = uri(it) }
    }
}

kotlin {
    experimental.coroutines = Coroutines.ENABLE
}

application {
    group = "de.swirtz"
    version = "1.0.0"
    applicationName = "gradle-kotlindsl"
    mainClassName = "de.swirtz.ApplicationKt"
}

publishing {
    repositories {
        maven {
            url = uri(nexusRepo)
        }
    }
    if (!project.hasProperty("jenkins")) {
        println("Property 'jenkins' not set. Publishing only to MavenLocal")
    } else {
        (publications) {
            "maven"(MavenPublication::class) {
                from(components["java"])
            }
        }
    }
}

tasks {
    withType<KotlinCompile> {
        kotlinOptions.jvmTarget = "1.8"
    }

    withType<Test> {
        testLogging.showStandardStreams = true
    }

    withType<Jar> {
        manifest {
            attributes["Main-Class"] = application.mainClassName
        }
        from(configurations.runtime.map { if (it.isDirectory) it else zipTree(it) })
    }

    withType<GradleBuild> {
        finalizedBy("publishToMavenLocal")
    }
}

The Result

We’ve seen a rather simple build script written with the Gradle Kotlin DSL. I made use of a few idiomatic Kotlin functions in order to show the power of such .kts files. Especially for Kotlin developers, it can make much sense to completely switch to the shown approach. IntelliJ does support the creation of new build.gradle.kts files by default when you open the “New” option in “Project” view.

There will be situations, which make you want to ask somebody for help. I recommend reaching out directly in the corresponding Kotlin Slack channel: gradle.

I hope I could inspire you to give it a try! Good Luck πŸ™‚

The whole script as a Gist

Please follow and like this Blog πŸ™‚
Kotlin Reified Types in Inline Functions

Kotlin Reified Types in Inline Functions

I’ve noticed that many people haven’t ever heard of reified types or have problems understanding what they are, and what they do. Therefore this little post is intended to bring some light into the darkness of Kotlin’s reified types.

Starting situation

fun <T> myGenericFun(c: Class<T>) 

In an ordinary generic function like myGenericFun you can’t access the type T because it’s, like in Java, erased at runtime and thus only available at compile time. Therefore, if you want to use the generic type as a normal Class in the function body you need to explicitly pass the class as a parameter like the parameter c in my example. That’s correct and works fine but makes it a bit unsightly for the caller.

Inlined function with reified to the rescue

If, on the other hand, you use an inline function with a reified generic type T, the value of T can be accessed even at runtime and thus you don’t need to pass the Class<T> additionally. You can work with T as if it was a normal Class, e.g. you might want to check whether a variable is an instance of T, which you can easily do like this: myVar is T.

An inline function with reified type looks like this:

inline fun <reified T> myGenericFun()

Be aware, that reified types can only be used in combination with inline functions. Such an inline function makes the compiler copy the function’s bytecode into every place where the function is being called (we say the function is being “inlined“). When you call an inline function with reified type, the compiler knows the actual type used as a type argument and modifies the generated bytecode to use the corresponding class directly. Therefore calls like myVar is T become myVar is String (if the type argument were String) in the bytecode and at runtime.

Reified in Action

Let’s have a look at an example, where reified is really helpful. We want to create an extension function for String called toKotlinObject, which tries to convert a JSON string to a Kotlin Object, specified by the function’s type T. We can use com.fasterxml.jackson.module.kotlin for this and the first approach is the following:

First approach without reified type

fun <T> String.toKotlinObject(): T {
      val mapper = jacksonObjectMapper()
                                    //does not compile!
      return mapper.readValue(this, T::class.java)
}

The readValue method takes a type that it’s supposed to parse the JsonObject to. If we try to get the Class of the type parameter T, the compiler complains: “Cannot use ‘T’ as reified type parameter. Use a class instead.”

Workaround with explicit Class parameter

fun <T: Any> String.toKotlinObject(c: KClass<T>): T {
    val mapper = jacksonObjectMapper()
    return mapper.readValue(this, c.java)
}

As a workaround, we pass the Class of T explicitly, which can directly be used as an argument to readValue. This works and is actually a common pattern in Java code for such scenarios. The function can be called like so:

data class MyJsonType(val name: String)

val json = """{"name":"example"}"""
json.toKotlinObject(MyJsonType::class)

The Kotlin way: reified

Using an inline function with reified type parameter T makes it possible to implement our function as follows:

inline fun <reified T: Any> String.toKotlinObject(): T {
    val mapper = jacksonObjectMapper()
    return mapper.readValue(this, T::class.java)
}

There’s no need to pass the Class of T additionally, T can be used as if it was an ordinary class. For the client the code looks like this:

json.toKotlinObject<MyJsonType>()

Important

Inline reified functions are not callable from Java code, whereas normal inline functions are. That’s probably the reason why not every type parameter used in inline functions is reified by default.

Conclusion

This was just a quick introduction to reified types. In my opinion the call to a function with reified types looks way better because we can make use of the <> syntax commonly used whenever generics are relevant. As a result, it’s more readable than the Java approach of passing a Class object as a parameter. All the dirty details can be read in this specification document.

If you want to read more about Kotlin’s beautiful features I recommend the book Kotlin in Action to you and also like to direct you to my other articles πŸ™‚

Please follow and like this Blog πŸ™‚
Kotlin Operator Overloading – Working by Convention

Kotlin Operator Overloading – Working by Convention

Operator Overloading and Conventions in Kotlin

Introduction

Kotlin supports a technique called conventions, everyone should be familiar with. For example, if you define a special method plus in your class, you can use the + operator by convention, Kotlin’s approach to operator overloading.
In this article I want to show you which conventions can be used and will provide some Kotlin code demonstrating the concepts of course.

Read More Read More

Please follow and like this Blog πŸ™‚

Enjoy this blog? Please spread the word :)