Sealed class in kotlin

Hi Everyone,

Today we gonna discuss Sealed class in kotlin, Sealed is a new class type that introduced by kotlin.

Sealed class –  Sealed classes are used for representing restricted class hierarchies when a value can have one of the types from a limited set.

whereas a subclass of a sealed class can have multiple instances which can contain state.

there are few rules that make a class as a sealed

  1. To declare a sealed class you have to put ‘sealed’ modifier before the name of the class.
  2. A sealed class is abstract by itself, it cannot be instantiated directly and can have abstract members.
  3. Sealed classes are not allowed to have non-private constructors
  4. A sealed class can have subclasses, but all of them must be declared in the same file as the sealed class itself. but that classes which extend subclasses of a sealed class can be placed anywhere, not necessarily in the same file.

Let’s see the example as per kotlin reference doc

sealed class Expr
data class Const(val number: Double) : Expr()
data class Sum(val e1: Expr, val e2: Expr) : Expr()
class Multi(val e1: Expr, val e2: Expr) : Expr()
object NotANumber : Expr()

above we define sealed class Expr and there other classes that extend Expr

The key benefit of using sealed classes comes into play when you use them with WHEN expression. If its possible to verify that the statement covers all cases, you don’t need to add an else clause to the statement.if you remove any of the cases it will throw compile time error.

fun eval(expr: Expr): Double = when(expr) {
    is Const -> expr.number
    is Sum -> eval(expr.e1) + eval(expr.e2)
    is Multi -> eval(expr.e1) * eval(expr.e2)
    NotANumber -> Double.NaN
// the `else` clause is not required because we've covered all the cases
}

 

let’s create other class that extends Multi class, here we can place Multi class child into other files.

class ArrayMulti(val x: Expr, val y: Expr) : Multi(x,y)

Now you can also call ArrayMulti class in WHEN expression, but Expr immediate child(e.g Multi class) must be there.

let’s see an example.

fun eval(expr: Expr): Double = when(expr) {
    is Const -> expr.number
    is Sum -> eval(expr.e1) + eval(expr.e2)
    is ArrayMulti -> eval(expr.e1) * eval(expr.e2)
    is Multi -> eval(expr.e1) * eval(expr.e2)
    NotANumber -> Double.NaN
// the `else` clause is not required because we've covered all the cases
}

Hope you like this. Thanks for reading 🙂

Advertisement

Data class in Kotlin

Hi Everyone,

Hope you like my earlier post on Kotlin (Java to kotlin part-1, java to kotlin part-2 and spring 5 reactive application using kotlin).

Kotlin has introduced many features,  in this post we will focus on data class.

 data –  A type of class that mainly use for hold a data. in such class, some standard functionality and utility functions are often mechanically derivable from the data.  we called data class in kotlin.

In case of data class compiler automatically derives the following members from all properties declared in the primary constructor:

#equals()/hashCode() pair.
# toString()
# componentN() functions corresponding to the properties in their order of declaration.
# copy() function

data classes have to fulfill the requirements:

# The primary constructor needs to have at least one parameters.
# All primary constructor parameters need to be marked as val or var.
# Data classes cannot be abstract, open, sealed or inner.
# (before 1.1) Data classes may only implement interface

let see the example of data class.

Now we are going to create a class with data prefix and define a primary parameterized constructor.

data class Customer(var id: Int,var name: String,var email : String)
//or you can define with default value
data class Customer(var id: Int,var name: String="",var email : String="test@gmail.com")

In the next step, we will be going to instantiate our customer class and print the customer object by using toString method.

var customer = Customer(1,"Nikesh","test@nikeshpathak.com")
println(customer.id)
println(customer.name)
println(customer.email)
println(customer.toString())

output:
1
Nikesh
test@nikeshpathak.com
Customer(id=1, name=Nikesh, email=test@nikeshpathak.com)

Now we will compare customer object using the equals method.

var customer = Customer(1,"Nikesh","test@nikeshpathak.com")
var customer1 = Customer(1,"Nikesh","test@nikeshpathak.com")
println(customer.equals(customer1))
customer1 = Customer(1,"Ritesh","test@nikeshpathak.com")
println(customer.equals(cus=tomer1))

output:
true
false

Note – Structural equality is checked by the equal/==  operation and referential equality is checked by the === operation.

We can Copy one object in another by using copy method.

var customer = Customer(1,"Nikesh","test@nikeshpathak.com")
var customer1 = customer.copy(2,"Ritesh")
println(customer1.id)
println(customer1.name)
println(customer1.email)

output:
2
test@nikeshpathak.com
Ritesh

using componentN (Destructuring declarations)

val (_,name,email) = customer

above syntax is called a destructuring declaration. A destructuring declaration creates multiple variables at once. we have declared two new variables name and email and can use them independently.

println(name)
println(email)

let’s take look example.

var customer = Customer(1,"Nikesh","test@nikeshpathak.com")
val (_,name,email) = customer
// println(id)
println(name)
println(email)

output:
Nikesh
test@nikeshpathak.com

Ref – Kotlin docs

Thanks for reading 🙂

Java to Kotlin part -2

Hello Everyone,

In this post, we will see object-oriented syntex and features in Kotlin. for other basic detail please visit the part-1 tutorial to make yourself comfortable.

let’s jump into code!

#using class

Java

class Customer {
}

Kotlin

class Customer {
}
//or if the class has no body then curley braces can be omitted
class Customer

 

#using constructor including primary and secondary 

Java

class Customer {

    String name;

    Customer() {}

    Customer(String name)
    {
        //TODO
    }
}

Kotlin

class Customer() {

    lateinit var name: String

    constructor(name: String) : this()
    {
        //TODO
    }
}

#using instance of class

Java

Customer customer = new Customer();
//or
Customer customer1 = new Customer("Test");

Kotlin

val customer  = Customer()
//or
val customer1 = Customer("Test")

#using inheritance 

Java

public class Base {

    Base(int p)
    {
        //TODO
    }
}
public class Derived extends Base{

    Derived(int p) {
        super(p);
    }
}

Kotlin

open class Base(p: Int)
class Derived(p: Int) : Base(p)

#using method overriding

Java

public class Base {

   final void v() {}
   void nv() {}
}
public class Derived extends Base{

    @Override
    void nv() {
        super.nv();
    }
}

Kotlin

open class Base {
    open fun v() {}
    fun nv() {}
}
class Derived() : Base() {
    override fun v() {}
}

#using static methods

Java

class Customer {

   static String name = "Test";
}

Kotlin

class Customer {

    companion object {
         var name : String = "Test"
    }
}

 

Thanks for reading 🙂

Java to kotlin part -1

Hello Everyone,

The purpose of this post to teach you kotlin syntax and new features based upon your current knowledge of java.

Kotlin is a statically-typed programming language that runs on the Java virtual machine and also can be compiled to JavaScript source code or use the LLVM compiler infrastructure. Its primary development is from a team of JetBrains programmers based in Saint Petersburg, Russia. As of Android studio, 3.0 kotlin is a fully supported programming language as well you can also write a server-side application in kotlin. you can also use kotlin to write build script in the gradle build system.

The best things you can directly use Java classes and library into kotlin and vice-versa

so let’s jump into code.

# print hello world

Java

public static void main(String[] args) {

    System.out.println("Hello World!");
}

Kotlin

fun main(args : Array)
{
    println("Hello World!")
}

# using variable 

Java

public static void main(String[] args) {

    final int a =1;
    final int b = 2;
    final int c;
    c = 3;
    int d =4;

    System.out.println(String.format("a = %d, b = %d, c = %d, d = %d", a, b, c, d));
}

Kotlin

fun main(args : Array)
{
    val a: Int = 1  // immediate assignment
    val b = 2   // `Int` type is inferred
    val c: Int  // Type required when no initializer is provided
    c = 3       // deferred assignment
    var d = 4  //Mutable variable
    println("a = $a, b = $b, c = $c, d = $d")
}

#using function with return and no parameter 

Java

public String message()
{
    return "Hello World";
}

Kotlin

fun message() : String
{
    return "Hello World"
}

#using function with void type and parameter 

Java

public void message(String message)
{
    System.out.println(message);
}

Kotlin

fun message(message : String) : Unit
{
    println("Hello World")
}

//or

fun message(message : String)
{
    println("Hello World")
}

#using conditional expression

Java

public int maxValue(int a, int b)
{
    if(a > b){
        return a;
    }else {
        return b;
    }
}

Kotlin

fun maxValue(a: Int, b: Int): Int {
    if (a > b) {
        return a
    } else {
        return b
    }
}

#using switch case(in case of kotlin we can using ‘when’)

Java

switch (args)
{
    case 1:
        System.out.println("One");
        break;
    case 2:
        System.out.println("Two");
        break;
        default:
           System.out.println("args is not 1 or 2");

}

Kotlin

when(args){
    1 -> println("One")
    2 -> println("Two")
    else -> {
        println("args is not 1 or 2")
    }
}

#using for loop

Java

String[] arrays = {"Apple", "Mango", "Orange"};
for(int i=0;i<arrays.length;i++)
{
    System.out.println(String.format("item at %d is %s",i,arrays[i]));
}

Kotlin

val items = arrayOf("Apple","Mango","Orange");
for (index in items.indices)
{
    println("item at $index is ${items[index]}")
}

#using while loop

Java

String[] arrays = {"Apple", "Mango", "Orange"};
int index = 0;
while(index < arrays.length)
{
    System.out.println(String.format("item at %d is %s",index,arrays[index]));
    index++;
}

Kotlin

val items = arrayOf("Apple","Mango","Orange");
var index =0
while (index < items.size)
{
    println("item at $index is ${items[index]}")
    index++
}

#using lambda

Java

String[] strArray =  {"Avocado","Mango","Apple","Orange","banana","Guava"};
List fruits = Arrays.asList(strArray);
fruits.stream().filter(s->s.startsWith("A")).sorted().map(s->s.toUpperCase())
        .forEach(s->{
            System.out.println(s);
        });

Kotlin

val fruits = arrayOf("Avocado","Mango","Apple","Orange","banana","Guava")
 fruits.filter { it.startsWith("a") }.sortedBy { it }.
         map { it.toUpperCase() }.forEach{ println(it)}

#using null values and checking for null

Java

public Integer parseInt(String str)
{
    try {
        return Integer.parseInt(str);
    }catch(NumberFormatException ex)
    {
        return null;
    }
}

Kotlin

fun parseInt(str: String) : Int?
{
    return str.toIntOrNull()
}
//incase if you call parseInt method with null input
fun parseInt(str: String?) : Int?
{
    return str?.toIntOrNull()
}

#using type checks

Java

public Integer getStringLength(Object obj)
{
    if(obj instanceof String)
    {
        return ((String) obj).length();
    }

    return null;
}

Kotlin

fun getStringLength(obj: Any): Int? {
    if (obj is String) {
        // `obj` is automatically cast to `String` in this branch
        return obj.length
    }

    // `obj` is still of type `Any` outside of the type-checked branch
    return null
}

Ref –  Kotlin docs

Part-2

Thanks for reading 🙂

Expose RESTful APIs using spring boot in 7 minutes

Hello Friends,

Today we are going to see how to expose standalone RESTful web services, the purpose of a post is to enable a reader to write their own restful web services.

Yes, that’s right! , I’m sure if you see complete video of this post you can write your RESTful web service.. ok enough talk 🙂 let’s start.

 

Hope you like this post. Thanks 🙂

 

 

Spring 5 reactive web application using kotlin

Spring has introduced webFlux new reactive web framework to support reactive programming.

Reactive programming?

“Reactive programming is about processing an asynchronous stream of data items, where applications react to the data items as they occur. A stream of data is essentially a sequence of data items occurring over time. This model is more memory efficient because the data is processed as streams, as compared to iterating over the in-memory data” (define at Oracle docs) .

For example, in an imperative programming setting, a = b +c would mean that a is being assigned the result of  b + c in the instant the expression is evaluated , and letter the values of b and/or c can be changed with no effect on the value of a, However, in reactive programming, the valud of a is automatically updated whenever the values of b and/or  c changes, without the program having to re-execute the sentence a= b + c to determine the presently assigned value of a (click here for more detail) .

Prerequisites :

Kotlin
Spring boot
Spring 5 webFlux and Reactive basic(RxJava or Project Reactor)
Spring data
Gradle

let generate spring boot template from Spring Initializr

Screen Shot 2017-11-26 at 11.13.34 AM

now import the generated project in your IDE and create Customer data class, check below example:-

Screen Shot 2017-11-26 at 11.35.48 AM

git link

@Document applied at the class level to indicate this class is a candidate for mapping to the database. You can specify the name of the collection where the database will be stored.

@Field applied at a variable level to define column name.

data class is specialized for hold data.

then created ‘Repository’ class look like below.

Screen Shot 2017-11-26 at 10.09.42 AM

git link

above class, I’ve extended ReactiveMongoReposiotry instead of MongoRepository because we are using Reactive features like Mono and Flux.

once ‘CustomerRepo’ repository classes created then create a handler for it, below code sample.

Screen Shot 2017-11-26 at 10.08.20 AM

git link

ServerRequest and ServerResponse introduce in spring 5, we can extract request param, path variable, header information and body details from ServerRequest.

Mono is a specialized Publisher that emits at most one item and then optionally terminates with an onComplete signal or an onError signal. click here for more detail.

Flux is a standard ‘Publisher’ representing an asynchronous sequence of 0 to N emitted items, optionally terminated by either a completion signal or an error. Thus, the possible values of a flux are a value, a completion signal, or an error. As in the Reactive Streams spec, these 3 types of signal translate to calls to a downstream object’s ‘onNext’, ‘onComplete’ or ‘onError’ methods. click here for more detail.

now we have handler and repository we need to expose endpoint, there is the magic of webFlux, you not need to create a separate class for it also get a ride from so much boilerplate, see below snippet.

Screen Shot 2017-11-26 at 10.07.39 AM

git link

Let me explain line by line,

@Configuration annotation indicates that a class declares one or more @Bean methods and may be processed by the Spring container to generate bean definitions and service requests for those beans at runtime.

@EnableReactiveMongoRepositories annotation is for Spring boot to enable reactive mongo repositories. if no base package is configured, in the case of spring boot application it is by default enable if you have include starter library.

@Bean is a method-level annotation and a direct analog of the XML element. The annotation supports most of the attributes offered by.

RouterFunction Central entry point to Spring’s functional web framework. Exposes routing functionality, such as to create a RouterFunction given a RequestPredicate and HandlerFunction, and to do further subroutine on an existing routing function.

HandlerFunction  Incoming HTTP requests are handled by a HandlerFunction, which is essentially a function that takes a ServerRequest and returns a Mono
let’s test whatever we have written, see below code snippet.

Screen Shot 2017-11-28 at 4.59.39 AM

git link

By default Spring webFulx include asynchronous natty server.

@RunWith(SpringRunner::class) Indicates that the class should use Spring’s JUnit facilities.

@SpringBootTest provides the following features over and above the regular Spring TestContext Framework,

  • Uses SpringBootContextLoader as the default ContextLoader when no specific @ContextConfiguration(loader=…) is defined.
  • Automatically searches for a @SpringBootConfiguration when nested @Configuration is not used, and no explicit classes are specified.
  • Allows custom Environment properties to be defined using the properties attribute.
  • Provides support for different webEnvironment modes, including the ability to start a fully running container listening on a defined or random port.
  • Registers a TestRestTemplate bean for use in web tests that are using a fully running container.

WebTestClient Non-blocking, reactive client for testing web servers. It uses the reactive WebClient internally to perform requests and provides a fluent API to verify responses.

WebTestClient can connect to any server over an HTTP connection. It can also bind directly to WebFlux applications using mock request and response objects, without the need for an HTTP server.

Conclusion

There are lots more features provided by Spring 5 and project reactor, I’ve introduced very basic sample on it. sample source available on my github .

Create spring beans using YAML

Spring highly adopted annotation based configuration and it is happily accepted by developer communities and why not, no one wants to struggle with XML tags but that’s not enough somewhere we still miss XML configuration or you can say external file configuration as powerful as XML configuration. especially when we write an application that has to alter behaviors without compilation.

But still writing an XML configuration is not readable and not easily understandable for beginners, so I’ve written experimental plugins for spring boot that convert YAML definition to Spring Beans.

here is an example of bean definition in XML and same in YAML.

Spring-beans.xml

Screen Shot 2017-11-04 at 6.45.07 PM

Spring-beans.yaml

Screen Shot 2017-11-04 at 6.44.14 PM

above code snippet, you can see a line of code and readability, let jump in a code example.

below code snippet, only need to add annotation “@ImportYamlResource” that will work same as “@ImportResource”

Screen Shot 2017-11-05 at 10.38.22 AM

below an example link, you can check out a project from git

yaml-beans-example

download library 

 

Note ->  YAML-spring-beans is a just experimental library, still there are lots of features not included

feedback will be much appreciated 🙂

Configure GitLab Runner with shell

Hi ,

I’ve found many examples where people configured with docker, if we need simple configuration for internal uses, we have also an alternative that can help to configure your GitLab CI runner easily.

In my usecase, i’m using Centos.

  1. add gitlab multi runner to yum repository

# curl -L https://packages.gitlab.com/install/repositories/runner/gitlab-ci-multi-runner/script.rpm.sh | sudo bash

2.once added to repository install gitlab-multi runner
#sudo yum install gitlab-ci-multi-runner

once gitlab runner install, it will create “gitlab-runner” user in your machine

may find here “/home/gitlab-runner” , gitlab-runner user do not have permission you need to add it to user group or something else whatever you need.

you can also see multiple commands provided by gitlab runner

#gitlab-runner –help

now ,we need to configure it with our gitlab hosted repository

#sudo gitlab-ci-multi-runner register 

Please enter the gitlab-ci coordinator URL (e.g. https://gitlab.com )
https://mygitlab.com/ci
Please enter the gitlab-ci token for this runner
xxx
Please enter the gitlab-ci description for this runner
my-runner
INFO[0034] fcf5c619 Registering runner… succeeded
Please enter the executor: shell, docker, docker-ssh, ssh?
shell
running already the config should be automatically reloaded!

————————————————-

after gitlab runner successfully configure you will see “admin area ->Runner” in gitlab

something similar to below images

Screen Shot 2016-10-08 at 5.29.43 PM.png

that is not completed yet you also need to configure Ci with include this file in your project root directory “”

added some configuration related to your project build and unit test running etc..

here is simple example i’ve added in “.gitlab-ci.yml” file

web_server_build:
script:
– cd spirng-mvc
– echo “making build”
– ./gradlew clean
– ./gradlew build

once configuration done, every commit we can run our build

Screen Shot 2016-10-08 at 5.55.33 PM.png

may I have skip few steps, let us know if require, I will update that.

Thanks for reading 🙂

Strategy pattern in java

Hi Friends,

today i want to share strategy pattern, of course this is very well known and mostly used pattern. and their is lots of use cases where we need to use strategic pattern.

#what is Strategy pattern?

The strategy pattern(also known as the policy pattern) is a software design pattern that enables an algorithm’s behavior to be selected at runtime. The strategy pattern. defines a family of algorithms, encapsulates each algorithm, and makes the algorithms interchangeable within that family. more

#When to use?

when we have multiple algorithm for a specific task and want to decides the actual implementation to be used at runtime

#Example

Suppose there is one software startup company and they have limited resource to done their work but all resource have multi-talented to do multiple roles,  like four resources (EmployeeA, EmployeeB, EmployeeC, EmployeeD) each one can able to done coding, testing,content writing etc. and any work can assign to anyone . its depend on availability.

Screen Shot 2015-10-22 at 3.10.43 AM

you can find example on Github link

Thanks

Chat application over xmpp protocol

Hi folk,

Today I’m going to share simple chat application that is based on xmpp protocol.

i know that you have lots of question  about xmpp , so simply i’m start with some definition or basic question.

# what is xmpp ?

xmpp is the extensible messaging and presence protocol, a set of open technologies for instant messaging,presence,multi-party chat, voice and video calls, collaboration, lightweight middleware, content syndication,and generalized routing of xml data.

XMPP was originally developed in the Jabber open-source community to provide an open, decentralized alternative to the closed instant messaging services at that time. click here for more detail.

# Why xmpp?

#Open standard – its gives you the choice and control about how you access your data and service.

#multi platform support – you can create chat application for the multiple platform over the xmpp protocol.

# xmpp implementation :

For the xmpp chat application we have to implement chat client and  configure server. firstly we are talking about chat client then we going to implement server configuration.

#Prerequisites

The following assumes that you have already basic knowledge in Android development with android studio.

1.Android studio

2.Smack 4.1 library (smack 4.1 supporting android for previous version we need to implement asmack  library).

#Example :

step 1 > Create a project in android studio(File -> New Project(add Application name,project location) -> check phone and teblet and select minimum sdk -> select activity type -> define activity name ->finish) for more detail how to manage a project in android studio click here

add library detail in build.gradle file as below.

build_gradle_config

step 2 > after adding library into project , now connect to openfire server and login as user.

Configuration_and_login

above this code example i have disable ssl and DIGEST-MD5 . According to your need you can enable it.

if you want to create user through your application then use AccountManager classto do it as for exp :

Account_manager step 3 > after successfully connected to chat server now create a chat with another user and receive there message.

 doChat_createchatmessageListner

Above this code i’ve created ‘doChat’ method where we need to pass userId(userId withwhome we want to chat) and implement ChatMessageListner to recive user message.

I hope a tutorial is helpful.

Thanks for reading 🙂