Skip to main content

Posts

enum in kotlin

ENUM Enums help us in defining like a fixed key-value pairs and then use them. These are to be used like fixed pairs and need not be stored in database or be something that shows up dynamically. These are mostly fixed entries. enum class ProductCategories ( val cat : String , val id : Int ) { ELECTRONICS ( "Electronics" , 0), ACCESSORIES ( cat = "Computer Accessories" , 1), PHERIPHERALS ( cat = "Computer Pheripherals" , id = 2); //This is a mandatory semi-colon fun getEnumId () = id fun categoryName () = cat } fun main (){ println ( ProductCategories . ACCESSORIES .categoryName()) println ( ProductCategories . PHERIPHERALS .categoryName()) }

anonymous objects in Kotlin

Anonymous Objects The benefit of using the anonymous objects is that they can be used to simplify usage rather than creating classes and then instantiating them and then consuming the functions. In this post, we are taking a simple interface and the interface is being used as an argument in a function. When we need to consume the method, we are required to create objects that are created from the classes that implement the interfaces. interface IPowerOfTwo { fun getPowerOf2 ( no : Int ): Int } fun printPowerOf2 ( powerOf2 : IPowerOfTwo ) { println ( "The value ^ 2 is : ${ powerOf2 .getPowerOf2(20) } " ) } Rather than creating the classes and instances, we can create an object on the fly and pass it as an argument to the function. fun main () { //The below method uses an anonymous object that has no class, yet implements the interface and gets the method ready for use printPowerOf2 ( object : IPowerOfTwo { override fun getPowerOf2 ( no : Int ) = no * n

Factory design pattern in Kotlin with companion objects

Factory Pattern The factory pattern helps the user to create the objects based on the inputs, so that the caller does not know how the object instances are created, instead focus on what are required to get me an instance of a given type. We start with a regular product, which has a constructor that takes the arguments and allows anyone to create the objects by invoking the appropriate constructor class RegularProduct { var skuId : String constructor ( sId : String ) { skuId = sId } constructor ( sId : String , upperCase : Boolean ) { skuId = if ( upperCase ) sId . toUpperCase () else sId . toLowerCase () } } //The private primary constructor restricts instantiation by any means other than factory class ProductWithFactory private constructor ( val sid : String ) { companion object { //Acts as a factory fun getProduct ( sid : String ): ProductWithFactory { return ProductWithFactory ( sid ) } fun getProduct ( si

Operations on Collections in Kotlin

Collections This post provides some of the operations that can be done in the collections using kotlin The below is the base type definitions that will be used in the below collection queries data class Shop ( val name : String , val customers : List < Customer >) data class Customer ( val name : String , val city : City , val orders : List < Order >) { override fun toString () = " $ name from ${ city . name } " } data class Order ( val products : List < Product >, val isDelivered : Boolean ) data class Product ( val name : String , val price : Double ) { override fun toString () = "' $ name ' for $ price " } data class City ( val name : String ) { override fun toString () = name } Operations on collections // Return a list of customers, sorted in the descending by number of orders they have made fun Shop. getCustomersSortedByOrders (): List<Customer> = this .customers.sortedByDescending( { it -> it.order

How to setup GPG keys in windows and configure the public key in github

GPG In this post today, we are going to look into the steps that we need to follow to generate and use a gpg  key with github Below given are the steps Installation Install  GnuPG for windows Validation of Installation Run the below command to verify if gpg is installed and working fine gpg --version Generate GPG key gpg --full-generate-key Running the above command will start running a command line wizard or sequence of steps, Choose the right length of the key Provide your username and email address Also provide a comment (Optional) Once done, approve with "O" Then the system will prompt for Key phrase, which will be used to secure the keys, so please remember and provide a secure value Listing the key List the keys that were generated as a result of the previous command using the below command gpg --list-secret-keys --keyid-format=long This command will produce a similar output gpg --list-secret-keys --keyid-format=long -------------------------------- pub   2048R/35F5FFB2

Range check in Kotlin

Introduction In many cases, we might be interested in checking dates to see if they fit in the range or numbers to see if they fall between the given range of numbers. Kotlin has a short hand way to represent the range which can be quite handy fun checkInRange(date: MyDate, first: MyDate, last: MyDate): Boolean {     return date in first..last } The above snippet of code is used to check the date (1st argument) lies between the first and the last date ranges.

Operator Overloading in Kotlin

Introduction The operator overloading feature let's us to build custom operators. In The below example, we provide a compareTo which can help us in evaluation of the <, >, = functions in the custom object of type MyDate data class MyDate( val year: Int , val month: Int , val dayOfMonth: Int ) : Comparable<MyDate> {     operator override fun compareTo(other: MyDate)= when {          year != other.year -> year - other.year         month != other.month -> month - other.month         else -> dayOfMonth - other.dayOfMonth     } } In the above snippet, we are implementing the Comparable<T>   for our MyDate type so that we can compare two instances of type MyDate as given below     println(date1 < date2) Capabilities This helps us in implementing custom operators to ease the use of business objects throughout the code rather than repeating code or using lots of Helpers in the code base.

Extension Functions in Kotlin

Introduction Extension functions help us a lot when implementing re-usable code. In many cases where we are required to provide re-usable code, but unable to add the function to the class may be because it was from a 3rd party library or from an external module, we end up adding a pile of helpers in getting the job done. In Java, this feature is not supported unlike in C# and other languages. The drawback of this is we have to create a helper class and create static methods which are not tied to the types. This results in helper classes being used and is not more readable than having the method as an extension or part of the type. data class RationalNumber( val numerator: Int , val denominator: Int ) fun Int.r(): RationalNumber = RationalNumber( this , 1 ) fun Pair< Int , Int >.r(): RationalNumber = RationalNumber( this .first, this .second) The above snippet explains the use of extension functions  which help us in extending the Integer and the Pair Types. After building t