Last Updated: September 19, 2018

Kotlin Reified Type

Description: In this post I'm gonna explain what is koltin reified types? with sample examples and explanation about its need and requirement in our application

If you are new to Koltin I recommend Switch from Java to Kotlin

So let's get started.



Why we need to know reified types?

Consider an below example in 'Java' which takes JSON and convert that into equivalent model class using Gson library (you can use any other parsing library like Jackson etc).

public T createModelFromClass(String jsonString) {
    return new Gson().fromJson(jsonString, T.class);
}

Now, if you try this way it will show an error saying "Cannot select from type variable". Because of "type erasure" in java generics which erased the type at run time.
Let's fix this!
public T createModelFromClass(String jsonString, Class<T> classT) {
    return new Gson().fromJson(jsonString, classT);
}

Consider the same example in kotlin

fun <T> createModelFromClass(jsonString: String): T {
    return Gson().fromJson(jsonString, T::class.java)
}
Now, if you try this way it will show an error saying ' Cannot use 'T' as reified type parameter. Use a class instead.

Because like in java the Generics 'T' get erased at run time.

Let's fix this!

fun <T: Any> createModelFromClass(jsonString: String, tClass: KClass<T>): T {
    return Gson().fromJson(jsonString, tClass.java)
}

Here comes the need!

In java and koltin example above, we need to pass the 'Class' so that the bytecode of the class could be generated at runtime.

Introducing reified type!
Reified in combination with inline function generates the bytecode of the class at runtime. So the overhead of passing <KClass> would be avoided within function.

How to use reified type?

Let's modify the above example of koltin using reified type




inline fun <reified T : Any> createModelFromClass(jsonString: String): T {
    return Gson().fromJson(jsonString, T::class.java)
}

Note: This functions with reified type are not callable from Java code.

Sample within the activity

class MainActivity : AppCompatActivity() {

    val USER_JSON = "{\"id\": 1000,\n" +
            " \"name\": \"nitesh tiwari\",\n" +
            " \"email\": \"nitiwari.dev@gmail.com\"\n" +
            "}"
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val userModel = createModelFromClass<User>(USER_JSON)
        Log.d("Reified", "\nName: " + userModel.name + "\nId:" + userModel.id + "\nEmail:" + userModel.email)
    }


    data class User(var id: Int, var name: String?, var email: String?)

    inline fun <reified T : Any> createModelFromClass(jsonString: String): T {
        return Gson().fromJson(jsonString, T::class.java)
    }
}


Output:

Name: nitesh tiwari
Id:1000
Email:nitiwari.dev@gmail.com


Bingo! We are done. We have just avoided the overhead of passing the 'KClass' in method constructor to generate its byte code at runtime.


Last Updated: April 09, 2018

Koltin Extension functions and Operator Overloading examples

Description: In this post I'm gonna explain you guys how 'Kotlin' gives us the power to play around with our code using 'Extension function' and 'Operator Overloading'.

Note: If you are new to Kotlin. I strongly recommend Switch from Java to Kotlin and Kotlinlang

So lets get started.



1. Kotlin Extension functions:

Why Extensions?
Extension empower as to extend the functionality of the existing classes without overriding the whole structure. Its fun !!!

Syntax:
fun <InheritingClassName>.<functionName>()

e.g : fun String.firstCharacterUpperCase(): String


Example 1:

Consider a requirement about making the first character 'CAPITAL' for logged in user in your app.

Using Extension:

fun String.firstCharacterUpperCase(): String {
    return if (this[0].isLowerCase())
        this[0].toUpperCase().plus(this.substring(1, this.length))
    else        this 
}

Explanation: This extension function return a String by making the first character in 'CAPITAL'

Note: 'this' means the inherited class. In our example its 'String'

So simply call:
fun printName(){
    val name = "nitesh tiwari".firstCharacterUpperCase()
    println("Name: $name")
}

//OutPut:
//Name: Nitesh tiwari


Example 2: 

Consider a requirement of getting a list on odd and even indexes respectively.

Using Extension:
fun <T> ArrayList<T>.oddEvenArrayItems(oddOrEven: Int): ArrayList<T> {
    val list = arrayListOf<T>()
    forEachIndexed { index, genericObject ->
        if (index % 2 == oddOrEven)
            list.add(genericObject)
    }
    return list
}

Explanation: This extension function returns generic ArrayList<T> whose index can we either odd or even based on input params.

So simply call:
fun printData(){
    val arrayList = arrayListOf<Int>(2,3,4,5,6,7,8,9,10, 11)
    val odd = arrayList.oddEvenArrayItems(1)
    val even = arrayList.oddEvenArrayItems(0)

    println("odd: $odd")
    println("even: $even")

    //OUTPUT
    //odd: [3, 5, 7, 9, 11]
    //even: [2, 4, 6, 8, 10]}

2. Operator Overloading:


Why Operator Overloading:
Operator overloading in Kotlin provide us the power to change the implementation of operators like plus(+),times(*),unaryplus(++),plusAssign(+=) and many many more on our 'Custom Objects'. Highly powerful !!!

Note: Operator names should be same.

Syntax:
operator fun <operatorName>()
e.g: operator fun plus()

Example 1: Consider a requirement where you want to add the price of the shopping cartItem together.

class CartItem(val price: Double, val name: String) {

    val itemName: String? = null
    operator fun plus(other: CartItem): Double =
        price + other.price
    
}

fun addPrice() {
    val cartItem1 = CartItem(10.6, "Bag")
    val cartItem2 = CartItem(20.4, "Shoes")

    val total: Double = cartItem1 + cartItem2
    println("Total Cost: $total")

    //OUTPUT:    //Total Cost: 31.0
}
Explanation: We have created a class 'CartItem' which contains the price of the shopping item and overridden the plus(+) operator for adding the prices together and returning the result. Looks simple right?.

Let's checkout one more example to understand operator overloading in combination of extension function


Example 2: Finding the item by productId in the List<CartItem>

class CartItem(val productId: Int, val price: Double, val name: String)

class Cart(val mList: List<CartItem>) {

    operator fun contains(id: Int): Boolean =
        mList.hasProductId(id)

    fun List<CartItem>.hasProductId(productId: Int): Boolean {
        forEachIndexed { _, cartItem ->
            if (productId == cartItem.productId)
                return true
        }
        return false
    }
}

fun checkProductId(){

    //Preparing CartItems
    val cartItem1 = CartItem(1001, 10.6, "Bag")
    val cartItem2 = CartItem(1002, 20.4, "Shoes")

    //Creating CartList
    val cartList = arrayListOf<CartItem>()
    cartList.add(cartItem1)
    cartList.add(cartItem2)

    //Creating Cart

   val cart = Cart(cartList)

    //Finding product
    println("Is 1001 present: " + cart.contains(1001))
    println("Is 1006 present: " + cart.contains(1006))
    
    //OUTPUT
    //Is 1001 present: true 
   //Is 1006 present: false
}

Explanation:
1. We have created a class 'Cart' which will be contain our listOf  'CartItem'.

2. Within our 'Cart' class we have overridden the 'contains' operator which will find whether the productId is within the 'Cart'

3. Finally, we have extension function(hasProductId) on List<CartItem> which returns a Boolean if the productId is present.

Example 3: Comparing two games together.

class GameItem(val scores: Double) {
    operator fun compareTo(item: GameItem): Int = this.scores.compareTo(item.scores)
}

fun compareGame() {

    val gameItem1 = GameItem(100.0)
    val gameItem2 = GameItem(2000.0)

    val result = gameItem1 > gameItem2

    println("Is game1 > game2 ? $result")
    
    //OUTPUT:    //Is game1 > game2 ? false}

Bingo we are done !!!

Let me know if you have any questions in comment box :-)

For more updates follow us on -  Twitter

#codingIsAnArt :-)