Kotlin Enum

How to use Kotlin Enum classes

Understanding Kotlin Enum

By Patrick Luck

Introduction

The enum class was one of the features of Java that has been brought over to Kotlin. At their core, Kotlin enum classes are classes that are declared by using the enum keyword in front of the class keyword. Since kotlin enum classes are classes, they are free to include methods, attributes, and they can even implement interfaces.

Enums are best used when you need to group a set of constants together. By grouping the constants into a single type, you can pass the type of the enum as a method parameter or use it as a return type later on in the program. Since you now have the benefit of having compiler checks, you are less likely to experience bugs in your program plus the added benefit of improvement readability in your code.

Enums can be highly flexible since they allow you to have attributes on them as well as methods. Allowing enums to implement interfaces allows for polymorphism, so you can keep your code loosely coupled which helps to maintain code. You can also add additional properties to a kotlin enum class if you need to store more information about a constant. Let’s look at a few uses of kotlin enum classes to best understand how to use them.

Declaring a Kotlin Enum

Example Kotlin Enum

enum class FoodMenu {
    BURGER,
    CHICKEN,
    GYRO
}

Explanation

Let’s suppose we have a restaurant that serves food and the food on the menu will never change. We should certainly represent that food in some sort of a class, but since we know it’s going to be constant, we can use an enum for it. In our case, we have three constants, BURGER, CHICKEN, and GYRO. We are free to add other items to the menu later on should we choose to do so but for now, we will stick with just the three food items.

It is simple enough to declare a kotlin enum. All we need to do is use the keywords enum class followed by our curly braces and then a comma separated list of constants. In this way, the enum class in Kotlin isn’t much different than the ones we see in Java. As a matter of fact, this is one of the features of Java that become available after Java 1.5 and is still widely used today.

There is an immediate advantage to using the enum. Right away, whenever we see FoodMenu.GYRO in our code, we know that GYRO belongs to FoodMenu. Had we used a regular constant, we would see GYRO but there is no context for having GYRO in our code. Should another developer come in and read our code, they will know that GYRO belongs to FoodMenu thanks to the fact that it’s an enum.

Using kotlin enum as a parameter

fun printMenuItem(foodMenu : FoodMenu)

fun printMenuItem(foodMenu: FoodMenu){
    when(foodMenu){
        FoodMenu.BURGER -> println("Burger")
        FoodMenu.CHICKEN -> println("Chicken")
        FoodMenu.GYRO -> println("Gyro")
    }
}

fun main(args: Array){
    printMenuItem(FoodMenu.BURGER)
    printMenuItem(FoodMenu.GYRO)
}

Explanation

One of the main uses for a Kotlin enum class is to use it as a parameter of a method. In the above example, we have declared a function printMenuItem that takes a FoodMenu as a parameter. Inside of the body of the function is a kotlin when function call that acts like a switch statement and reacts accordingly. Since we used an enum as a parameter rather than a Long or a String, the compiler can check for us that all case statements are covered. Not only does this make the code more readable, but it also makes it more robust since if we add more food items later on to our kotlin enum class, the compiler will force use to either add an else branch to the kotlin when or add the new food item to it.

Later on in the code example, we call the printMenuItem function in the main function. As you can see from the code, we are passing in FoodMenu.BURGER and FoodMenu.GYRO into the parameter. Anyone who is reading this code will see that these constants are FoodMenu items and will understand the purpose of the constants.

Advanced Enums

PrintableFood and Displayable

interface Displayable {
    fun diplay()
}

enum class PrintableFood(val displayName : String) : Displayable {

    BURGER("Burger") {
        override fun diplay() = println(this.displayName)
    },
    CHICKEN ("Chicken Sandwich") {
        override fun diplay() = println("Printing ${this.displayName}")
    },
    GYRO ("Pork Gyro") {
        override fun diplay() = println("Getting a Greek ${this.displayName}")
    }
}

fun displayMenuItem(displayable: Displayable)
        = displayable.diplay()

fun main(args: Array){
    PrintableFood.values().forEach { it -> displayMenuItem(it) }
}

Explanation

As mentioned earlier, kotlin enum classes can have attributes and methods. This example starts with an interface Displayable that declares a display() method. Next we have a kotlin enum class that will implement the interface. You will notice that this class has a constructor that takes a String parameter and it also implements the Displayable interface.

Let’s start with the attribute first. Since this enum has a displayName property, it will have to initialize that property. We do that by adding a () after the name of the constant and passing a value to it. This is why you now see BURGER (“Burger”) rather than BURGER. Going forward, we can now call PrintableFood.BURGER.displayName and it will have the “Burger” String stored in that variable. We actually use the property when we implement the display() method in the class.

Just like in Java, a kotlin enum can implement an interface. However, each instance of the enum has to implement the interface, which is why we now have a class body after each declaration of the enum. This can allow for additional polymorphism in the class since each value in the enumeration isn’t forced to have the same implementation as the others.

Since PrintableFood implements Displayable, it can be used in any method that takes a Displayable variable. We see this in the main method where we go through each value in the PrintableFood enum and call displayMenuItem on it. Each value in PrintableFood will call the proper implementation of display() and print the correct value to the console.

Conclusion

Whenever you need to group constants together, you should consider using a kotlin enum. Doing so will make your code more readable and it will even offer protection against bugs through compiler checks. Since kotlin enum classes are just like any other class, they are free to declare attributes, methods, and even implement interfaces. For this reason, they are highly flexible and can be used to develop robust, readable, and loosely coupled code.

Enums also work great with kotlin when since the compiler will check and make sure that all cases of the enumeration are covered. This will help you maintain your code later on as you add values or remove them from your enum class. The kotlin compiler will force you to cover all cases of the enum or add an else block to it.

Github

You can get the code at https://github.com/archer920/Kotlin-Enum

You may also like

  1. Three uses for kotlin when
  2. Consuming REST with Spring and Kotlin
  3. Kotlin Scheduling Tasks with Spring Boot
  4. Kotlin Command Line Compile
  5. Kotlin String Formatting

Sources

  1. https://kotlinlang.org/docs/reference/enum-classes.html
  2. https://kotlinfrompython.wordpress.com/2017/10/16/enum/
  3. https://en.wikipedia.org/wiki/Enumerated_type
  4. http://www.codemag.com/Article/050104/Improve-Code-with-Enums
  5. https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html
Advertisements

Three uses for Kotlin When

Three uses for Kotlin When

Replace the if when

By Patrick Luck

Introduction

The kotlin when extension function is part of the Kotlin standard library and it is used to replace both the switch statement as well as the if-else statements. It is critical that you understand when to use the kotlin when function because when used properly, when can greatly increase the readability of your code. There are three primary different uses where using kotlin when is practical. The first case is comparing a value and then executing the proper branch of code when a true condition has been found. The second involves returning a value based on a try condition. Finally, when is also useful for exception handling.

Like switch and if-else, kotlin when allows you to specify a default case that will execute when none of the specified conditions have been found. A default case is optional as long as when is not being used to return a value. In other words, should you use the kotlin when function to return a value, you will be forced to include an else block in the function or the compiler will flag an error. However, as long as you are not returning a value by using kotlin when, you will not be required to have a default case. Let’s take a look at a few examples of using when in a real program.

Executing a block of code based on a condition

fun throwException(name : String)

fun throwException(name: String){
    when (name) {
        "RuntimeException" -> throw RuntimeException("RuntimeException")
        "IllegalArgumentException" -> throw IllegalArgumentException("IllegalArgumentException")
        "IndexOutOfBoundsException" -> throw IndexOutOfBoundsException("IndexOutOfBoundsException")
        else -> println("Not an exception")
    }

}

Explanation

Here is a function that throws an exception based on the name String parameter. In this case, we are using the kotlin when function to replace a switch or an if-else-else-if block. As you can see, the kotlin when function makes the code highly readable. We start by passing the name variable to when which allows the function to compare the value in name to the values listed on the left side of the ->. Our first value is “RuntimeException” so when name == “RuntimeException” the code to the right of the -> will execute and a RuntimeException is thrown.

The same logic holds true for the two other cases as well. When name == “IllegalArgumentException” the code to the right of -> next to “IllegalArgumentException” is executed and an IllegalArgumentException is thrown by the JVM. The same is also the case for “IndexOutOfBoundsException”.

Finally, we also have an else in this when function. The else acts like a default in a Java switch statement or as an else in an if block. In our case, when name isn’t “RuntimeException”, “IllegalArgumentException”, or “IndexOutOfBoundsException”, then the code to the right of the -> next to the else block executed and we print “Not an exception” to the console.

Exception Handling

fun handleException(name : String)

fun handleException(name : String){
    try {
        throwException(name)
    } catch (e : Exception){
        when (e) {
            is IllegalArgumentException -> println("Handling an IllegalArgumentException")
            is IndexOutOfBoundsException -> println("Handling an IndexOutOfBoundsException")
            is RuntimeException -> println("Handling a Runtime Exception")
        }
    }
}

Explanation

This is an example of when we are using the kotlin when function for exception handling. Developers who are familiar with Java will likely remember using multiple catch blocks for each kind of exception that they wanted to handle. Every kind of unique exception type had to have its own catch block until Java 7 when multi-catch handlers were introduced for when you wanted to use the same code to handle different exception types. However, using a unique catch block for every kind of or groups of exceptions was cumbersome and lead to a lot of boiler plate in your code.

Kotlin addressed this issue by allowing the when function to be combined with the is operator. Keep in mind that “is” is used to compare the type of an object with a class to see if object is of a specific type and return true or false accordingly. That means we have a boolean operation here which allows it to be used with when. For example, when e is IllegalArgumentException, we execute the code to the right of the -> and print “Handling an IllegalArgumentException”. Not only does this improve the readability of the code by allowing for a plain english construct, but we also do away with all of the catch blocks that we would have needed in Java.

Returning a value

fun returnFromWhen(name : String): Class?

fun returnFromWhen(name : String): Class? {
    return when(name){
        "RuntimeException" -> RuntimeException::class.java
        "IllegalArgumentException" -> IllegalArgumentException::class.java
        "IndexOutOfBoundsException" -> IndexOutOfBoundsException::class.java
        else -> {
            println("Returning a null value")
            null
        }
    }
}

Explanation

Our final case is for using when to return a value. This is a powerful construct because it allows us to avoid declaring intermediate variables in a function just for the purpose of returning a value. It also allows us to avoid multiple exit points in a function which many developers consider to be a bad practice since it can be prone to bugs.

Since when is a function, it can be combined with the return keyword to return a value. Should you decide to use this feature, you will need to keep in mind that the returning value needs to be the last statement in a block of code following the -> in each case of the when. The type of return value also had to be declared in the calling function as well, which is what we have in the function declaration.

The kotlin when function works the same as it does in the other two cases. We pass a variable to it and then compare it to the separate cases. The only difference is that the final statement in the code of the -> needs to be a return value of some sort. In our case, we are returning Class objects that extend from RuntimeException. Our function has also been declared as nullable so that we can return null. After each case in the when block, we return a Class object, except for the else case which returns null.

You will notice also that the else part has { } that wraps multiple statements. This can always be done with the kotlin when function and will allow you to execute a block of code when it is needed.

Conclusion

As you may have noticed, the kotlin when function is a great tool to use when you need to increase the readability of your code by allowing you to avoid if else statements. It is also more powerful than the Java switch statement, as you are free to use any boolean condition in the when statement. The most common patterns for using kotlin when is to execute a block of code, exception handling, and returning a value.

Many developers execute a block of code using kotlin when just as if they are using a Java switch statement. In this case, we are checking a value against different conditions and then acting accordingly. Using kotlin when in this fashion is more flexible than using a switch statement, because you are not limited to just numeric or String values. Kotlin when allows you to do any legal comparisons which makes it more powerful than a Java switch statement.

The kotlin when function is also used to avoid a messy list of catch blocks when you are handling exceptions. Instead, you can use the “is” operator to check the type of your exception object and respond as needed to the exception. This allows for more compact exception handling than what you can normally achieve in Java.

Finally, since kotlin when is a function, you can use it to return a value. This allows you to avoid having multiple exit points in your function and you can avoid needing to declare an unnecessary variable. Once again, this makes your code more concise and readable that what you can normally achieve in other programming languages.

Github

You can find the entire code for this post at https://github.com/archer920/Koltin-When-Exception

Sources

  1. https://kotlinlang.org/docs/reference/control-flow.html
  2. http://www.baeldung.com/kotlin-when
  3. https://www.programiz.com/kotlin-programming/when-expression
  4. https://antonioleiva.com/when-expression-kotlin/
  5. https://www.tutorialkart.com/kotlin/when-expression-in-kotlin/

Consuming REST with Spring and Kotlin

Spring 5 came with official support for Kotlin, a JVM language developed by Jetbrains which focuses on code clarity and conciseness. Many web applications today are a mockup of content from other websites, which are usually exposed with a web service. Consuming a web service is really easy when you use Spring’s RestTemplate class. This tutorial is an adaptation of the one found here, which has been modified to use the Kotlin language.

Project Structure

You will want to setup your project with a folder structure that is similar to the one shown in the screenshot below.

consuming_rest

build.gradle

Next you will want to use a dependency management system, either gradle or maven, which will see to the details of downloading your dependencies. We use gradle in this tutorial.

buildscript {
    ext.kotlin_version = '1.2.30'

    repositories {
        mavenCentral()
    }
    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath("org.springframework.boot:spring-boot-gradle-plugin:2.0.1.RELEASE")
    }
}

group 'com.stonesoupprogramming'
version '1.0-SNAPSHOT'

apply plugin: 'kotlin'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'

bootJar {
    baseName = 'gs-consuming-rest'
    version =  '0.1.0'
}

repositories {
    mavenCentral()
}

dependencies {
    compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version"
    compile group: 'org.jetbrains.kotlin', name: 'kotlin-reflect', version: '$kotlin_version'
    compile("org.springframework.boot:spring-boot-starter")
    compile("org.springframework:spring-web")
    compile("com.fasterxml.jackson.core:jackson-databind")
}

compileKotlin {
    kotlinOptions.jvmTarget = "1.8"
}
compileTestKotlin {
    kotlinOptions.jvmTarget = "1.8"
}

ConsumingRest.kt

Now we are going to write a simple Kotlin application which will make an HTTP GET request to a server and deserialize the JSON into Kotlin object. We will use two data classes and then write a main function. Here is the code.

package com.stonesoupprogramming

import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import org.springframework.web.client.RestTemplate

/**
 * The following data classes are instantiated by Jackson and converted from JSON to
 * objects. Normally, the class needs to have all of the properties in the JSON, but
 * we can change this by using the ignoreUnknown = true argument
 */
@JsonIgnoreProperties(ignoreUnknown = true)
data class Value(var id: Long = 0, var quote: String = "")

@JsonIgnoreProperties(ignoreUnknown = true)
data class Quote(var type : String = "", var value : Value? = null)

fun main (args : Array){
    //Create a new RestTemplate and use getForObject to make a GET request
    //to the server and return an instance of Quote representing the response
    val quote = RestTemplate().getForObject("http://gturnquist-quoters.cfapps.io/api/random", Quote::class.java)

    //Print the response to the console
    println(quote)
}

Our application begin by declaring two data classes which are Value and Quote. We annotate these classes with @JsonIgnoreProperties which allows the JSON deserializer to skip over JSON properties that are not present in our data classes. Otherwise, we would get a runtime exception. The JSON deserializer uses reflection (java based) to instantiate objects from the data classes so we need some form of a default constructor. We can do this a number of different ways in Kotlin, but I chose to use default values the properties in the data classes.

Next we have a main function. It starts by creating a new RestTemplate object and calling its getForObject method. The getForObject requires a web address and a class of the object to return. Then we call println on the returned Quote object to print the output to the console.

RestTemplate has methods for just about every HTTP verb so while this example only uses GET, you can do POST, PUT, DELETE and other common web requests.

Output

The output will different every time you run the application, but here is what I got when I ran it.

14:47:14.091 [main] WARN org.springframework.http.converter.json.Jackson2ObjectMapperBuilder - For Jackson Kotlin classes support please add "com.fasterxml.jackson.module:jackson-module-kotlin" to the classpath
14:47:14.156 [main] DEBUG org.springframework.web.client.RestTemplate - Created GET request for "http://gturnquist-quoters.cfapps.io/api/random"
14:47:14.247 [main] DEBUG org.springframework.web.client.RestTemplate - Setting request Accept header to [application/json, application/*+json]
14:47:14.321 [main] DEBUG org.springframework.web.client.RestTemplate - GET request for "http://gturnquist-quoters.cfapps.io/api/random" resulted in 200 (OK)
14:47:14.322 [main] DEBUG org.springframework.web.client.RestTemplate - Reading [class com.stonesoupprogramming.Quote] as "application/json;charset=UTF-8" using [org.springframework.http.converter.json.MappingJackson2HttpMessageConverter@cc43f62]
Quote(type=success, value=Value(id=1, quote=Working with Spring Boot is like pair-programming with the Spring developers.))

Conclusion

Here is the source document for this tutorial.

https://spring.io/guides/gs/consuming-rest/

You can get the code at my github at this address: https://github.com/archer920/consuming-rest

Kotlin Scheduling Tasks with Spring Boot

Kotlin is fully interoperable with Spring Boot which makes Spring and Kotlin a perfect companion to one another. Spring brings a high level platform that can be used for making just about any enterprise grade application, while Kotlin offers language features that make your code concise and readable. Both Kotlin and Spring do a great job of reducing boilerplate in your code so that you can write an application quickly and get to the point.

This tutorial is based on Scheduling Tasks found on the Spring website is an adapation of the tutorial for Kotlin. We will be using Kotlin, Spring Boot, and Gradle. You can find the code here.

Project Structure

You should setup your project to use this folder structure.

scheduling_tasks

build.gradle

Here is the full code for your gradle.build file. Notice that will bring in both Kotlin and Spring libraries so that we can build the project.

buildscript {
    ext.kotlin_version = '1.2.30'

    repositories {
        mavenCentral()
    }
    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath "org.springframework.boot:spring-boot-gradle-plugin:2.0.1.RELEASE"
    }
}

group 'com.stonesoupprogramming'
version '1.0-SNAPSHOT'

apply plugin: 'kotlin'
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'

repositories {
    mavenCentral()
}

bootJar {
    baseName = 'gs-scheduling-tasks'
    version =  '0.1.0'
}

sourceCompatibility = 1.8
targetCompatibility = 1.8

dependencies {
    compile "org.springframework.boot:spring-boot-starter"
    compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version"
    compile group: 'org.jetbrains.kotlin', name: 'kotlin-reflect', version: '1.2.30'
    testCompile "junit:junit"
}

compileKotlin {
    kotlinOptions.jvmTarget = "1.8"
}
compileTestKotlin {
    kotlinOptions.jvmTarget = "1.8"
}

SchedulingTasks.kt

Here is the Kotlin code followed by an explanation.

package com.stonesoupprogramming.schedulingtasks

import org.slf4j.LoggerFactory
import org.springframework.boot.SpringApplication
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.scheduling.annotation.EnableScheduling
import org.springframework.scheduling.annotation.Scheduled
import org.springframework.stereotype.Component
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter

/**
 * Mark this class an injectable component so that the Spring environment will create
 * an instance of this class when it starts up.
 */
@Component
class ScheduleTasks {

    private val logger = LoggerFactory.getLogger(ScheduleTasks::class.java)

    /**
     * This @Schedule annotation run every 5 seconds in this case. It can also
     * take a cron like syntax.
     * See https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/scheduling/support/CronSequenceGenerator.html
     */
    @Scheduled(fixedRate = 5000)
    fun reportTime(){
        logger.info("The time is now ${DateTimeFormatter.ISO_LOCAL_TIME.format(LocalDateTime.now())}")
    }
}

@SpringBootApplication
//Required to tell Spring to run tasks marked with @Scheduled
@EnableScheduling
open class Application

fun main(args : Array){
    SpringApplication.run(Application::class.java)
}

When run, you will get this output on your console every five seconds.

2018-04-06 18:51:21.868  INFO 20294 --- [pool-1-thread-1] c.s.schedulingtasks.ScheduleTasks        : The time is now 18:51:21.865
2018-04-06 18:51:26.858  INFO 20294 --- [pool-1-thread-1] c.s.schedulingtasks.ScheduleTasks        : The time is now 18:51:26.858

Explanation

So how does the code work? The ScheduleTasks class is annotaded with @Component, which the Spring environment scans for on start up and instantiates the class. At this point, an instance of ScheduleTasks lives in the ApplicationContent. You will notice that the ScheduleTasks::reportTime function is annotated with @Scheduled which defaults to a fix rate or can use a CRON like syntax.

You can’t annotate a method and expect it to run without turning on scheduling. That is why the Application class is annotated with @EnableScheduling. This will tell Spring to scan all container managed classes and look for the @Scheduled annotation. The Spring environment will do the job of making sure that the methods run at the proper time.

Code

You can get the code for this tutorial at my GitHub: https://github.com/archer920/scheduling-tasks

Sources

https://spring.io/guides/gs/scheduling-tasks/
https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/scheduling/support/CronSequenceGenerator.html

Build a RESTful Web Service with Kotlin

Introduction

Spring and Kotlin combine together to create a powerhouse when it comes to rapid application development. The Spring project is a powerful framework that allows you to develop an application quickly with as little boilerplate and configuration code as possible. Kotlin is a language that is developed Jetbrains that focuses on code readability and conciseness. This guide will show you how to build a RESTful web service using Spring Boot and Kotlin.

Getting Started

We will use a Maven project to mranage the resources that this application will need. Your project will need the following folder skeleton before you can continue.

Maven

After you have created your project skeleton you can continue.

pom.xml

The pom.xml file is used by Maven to manage all of your project dependencies. You can copy and paste this code into your pom.xml file, which will pull in all of the Spring Boot and Kotlin dependencies.



    4.0.0

    stonesoupprogramming
    BuildingRESTfulWebService
    1.0-SNAPSHOT

    
        1.2.31
    

    
        org.springframework.boot
        spring-boot-starter-parent
        2.0.0.RELEASE
    

    
        
            org.jetbrains.kotlin
            kotlin-stdlib-jdk8
            ${kotlin.version}
        
        
            org.jetbrains.kotlin
            kotlin-reflect
            ${kotlin.version}
        
        
            org.reflections
            reflections
            0.9.10
        
        
            org.jetbrains.kotlin
            kotlin-test
            ${kotlin.version}
            test
        

        
            org.springframework.boot
            spring-boot-starter-web
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        
        
            com.jayway.jsonpath
            json-path
            test
        
    

    
        src/main/kotlin
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
            
                org.jetbrains.kotlin
                kotlin-maven-plugin
                ${kotlin.version}
                
                    
                        compile
                        compile
                        
                            compile
                        
                    
                    
                        test-compile
                        test-compile
                        
                            test-compile
                        
                    
                
                
                    1.8
                
            
        
    

    
        
            spring-releases
            https://repo.spring.io/libs-release
        
    
    
        
            spring-releases
            https://repo.spring.io/libs-release
        
    

Application.kt

Kotlin is a language that is meant to be concise, which plays to our advantage. We will hold all of our classes inside of the Application.kt file.

package com.stonesoupprogramming.spring.boot

import org.springframework.boot.SpringApplication
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.RestController
import java.util.concurrent.atomic.AtomicLong

/**
 * This class gets converted into JSON and serves as our data model.
 * We can use Kotlin's data class feature to make it only one line of code.
 */
data class Greeting (val id : Long, val content : String)

/**
 * The @RestController annotation tells the Spring Environment to
 * use this class to handle REST requests. That means that it will handle
 * HTTP requests but does not use a view technology to write the response.
 * Instead, an instance of Greeting is simply converted into JSON and written
 * to the HTTP response body.
 */
@RestController
class GreetingController {

    private val counter : AtomicLong = AtomicLong()

    /**
     * The @RequestMapping signals that this method will handle
     * HTTP requests to /greeting. We can narrow it down to GET, POST, PUT, etc
     * when we want different methods to handle different requests
     * at this endpoint.
     *
     * The name parameter is annotated with @RequestParam which has
     * two arguments. The name argument maps the request parameter name to
     * the name argument in this method. The defaultValue will populate
     * name with the value "World" if the request does not have a name argument.
     */
    @RequestMapping("/greeting")
    fun greeting(@RequestParam(value="name", defaultValue="World") name : String) : Greeting {
        return Greeting(counter.incrementAndGet(), "Hello $name")
    }
}

/**
 * The @SpringBootApplication is a meta annotation that makes
 * this application executable.
 */
@SpringBootApplication
open class Application

/**
 * Now we just need an entry point to the program.
 */
fun main(args : Array){
    SpringApplication.run(Application::class.java, *args)
}

Let’s break the code down into each piece.

Greeting

Greeting is a data class that has two fields, id and content. Kotlin introduced data classes to cut down on boilerplate code when using POJOs (Plain old java object). It will have all of the getters, equals, hashcode, and toString() as well as a constructor. This class will get converted into JSON and written to the response body later on in the application.

GreetingController

Spring works on a Model, View, Controller architecture so it uses Controller classes to map web requests to backend code. In this case, we are using @RestController to specify that we are not using a view technology to generate HTML and are instead going to write JSON to the HTML response body.

This class only has one method, greeting, which is annotated with @RequestMapping. You will use @RequestMapping to map HTTP requests to a method in the class. In our case, we are mapping all requests (GET, PUT, POST, DELETE) to /greeting to our greeting method. The greeting method has one argument, name, which is also annotated with @RequestParam.

The @RequestParam has two arguments, value which specifies the name of the argument in the request and the default value if the argument is not present in the request. In our case, we also called the request parameter name and we have it default to World. Inside of the method, we return a new instance of Greeting and then return it. The Spring environment will see to the details of converting it to JSON and writing it to the response.

Application

We also have an empty Application class that is marked with the @SpringBootApplication annotation. This is a meta-annotation that pulls in all of the annotations that are needed to make this program executable. We using it in the main function to start the program.

Finishing

After you start the application, you can point your browser to

http://localhost:8080/greeting and then http://localhost:8080/greeting?name=User to see the JSON output of this application.

Sources

https://spring.io/guides/gs/rest-service/

https://kotlinlang.org/docs/reference/

Source

The source code for this project is available on my github here: https://github.com/archer920/BuildingRESTfulWebService

Python Color Chooser

The tkinter library in Python comes with an askcolor function that will pull up the system’s color picker dialog. It’s really easy to use and it returns a tuple with a RGB value and a hexadecimal value. This makes it really easy for anyone who is working with colors to ask the user for a color.

from tkinter import *
from tkinter.colorchooser import askcolor


class Window(Frame):
    def __init__(self, master=None, cnf={}, **kw):
        super().__init__(master, cnf, **kw)
        self.open = Button(self, text='Pick a color', command=self.pick_a_color)
        self.exit = Button(self, text='Exit', command=self.quit)

        for b in (self.open, self.exit):
            b.pack(side=LEFT, expand=YES, fill=BOTH)
        self.pack()

    def pick_a_color(self):
        print(askcolor(parent=self, title='Pick a color'))


if __name__ == '__main__':
    win = Window(Tk())
    win.mainloop()

askcolor

The askcolor function simply shows the system’s ask color dialog window. Therefore, it will adjust to the user’s platform and look natural. You can add the parent and title arguments if you want but otherwise the defaults work just as well.

Calling the function only requires one line of code.

askcolor(parent=self, title='Pick a color')

When the user picks a color, a tuple is returned with the rgb values and the hexadecimal values.

((255.99609375, 170.6640625, 104.40625), '#ffaa68')

You will get this result if they click on cancel.

(None, None)

Notice that it is a tuple of None.

Python File Dialog

Many Python applications need to ask the user if they want to a open a file or folder or save a file. The tkinter library has built in dialog functions for this exact purpose. Here is an example of how to use the askopenfilename, asksaveasfile, and askdirectory functions with some common configurations.

from tkinter import *
from pathlib import Path
from tkinter.filedialog import askopenfilename, asksaveasfile, askdirectory


class Window(Frame):
    def __init__(self, master=None, cnf={}, **kw):
        super().__init__(master, cnf, **kw)
        self.open = Button(self, text='Open', command=self.open_file)
        self.save = Button(self, text='Save', command=self.save_file)
        self.ask_dir = Button(self, text='Folder', command=self.ask_folder)
        self.exit = Button(self, text='Exit', command=self.quit)

        for b in (self.open, self.save, self.ask_dir, self.exit):
            b.pack(side=LEFT, fill=BOTH)

        self.pack()


    def open_file(self):
        file = askopenfilename(filetypes=(("Python files", "*.py"),
                                           ("All files", "*.*")),
                               title='Open File',
                               initialdir=str(Path.home()))
        if file:
            print(file)
        else:
            print('Cancelled')

    def save_file(self):
        file = asksaveasfile(filetypes=(("Python files", "*.py"),
                                           ("All files", "*.*")),
                               title='Save File',
                               initialdir=str(Path.home()))
        if file:
            print(file)
        else:
            print('Cancelled')

    def ask_folder(self):
        folder = askdirectory(title='Pick a folder', initialdir=str(Path.home()))

        if folder:
            print(folder)
        else:
            print('Cancelled')


if __name__ == '__main__':
    win = Window(Tk())
    win.mainloop()

askopenfilename

You use askopenfilename when you want to open a file. It will return the absolute path of the file as a string if the user picks a file, or it will return None if the user cancels. You can restict the file types by passing an Iterable of tuples to the filetypes argument. If you do not specify an initialdir argument, it will default to the root of the user’s disk. I usually prefer to set it to the user’s home directory using Path.home() but you can adjust this to your application’s needs. The dialog will look specific to the user’s platform.

def open_file(self):
    file = askopenfilename(filetypes=(("Python files", "*.py"),
                                       ("All files", "*.*")),
                           title='Open File',
                           initialdir=str(Path.home())
    if file:
        print(file)
    else:
        print('Cancelled')

asksaveasfile

You can use this dialog when you want to perform a save operation. It takes arguments that are similar to askopenfilename, but it will return a file handler object opened in write mode (if you use the default arguments) rather than a string. You can then proceed with your save code. This function also returns None if the user cancels.

def save_file(self):
    file = asksaveasfile(filetypes=(("Python files", "*.py"),
                                       ("All files", "*.*")),
                         title='Save File',
                         initialdir=str(Path.home()))
    if file:
        print(file)
    else:
        print('Cancelled')

askdirectory

This function is used to let the user pick a folder. It will return a string if the user picked a folder or None if they chose to cancel.

def ask_folder(self):
    folder = askdirectory(title='Pick a folder', initialdir=str(Path.home()))

    if folder:
        print(folder)
    else:
        print('Cancelled')