The cast can never be succeed


I am new in Kotlin and I currently study about the concept of OOP

I am trying to do a cast with this code, but I’m facing an error:

    open class Operations1(){
        open  fun sum(n1:Int , n2:Int):Int{
            return n1+ n2
        fun sub(n1:Int , n2:Int):Int{
            return n1- n2
    class multiOperations1():Operations(){
        override  fun sum(n1:Int , n2:Int):Int{
            return n1+ n2 +5
        fun mul(n1:Int , n2:Int):Int{
            return n1* n2
        fun div(n1:Int , n2:Int):Int{
            return n1/ n2
    fun main(args:Array<String>){

        var oper  Operations()
        var inlit   multiOperations1() as Operations1
        println("Enter first number")
        var n1:Int  readLine()!!.toInt()
        println("Enter Second Number")
        var n2:Int  readLine()!!.toInt()

        var sum  inlit.sum(n1 , n2)
        var sub  inlit.sub(n1 , n2)
        println("Sum: " + sum)
        println("Sub: " + sub)

Screen shot of the code

This is the screen shot of the code


This is the error which my program through


To achieve you can use Gson and avoid boilerplate code.

var operation Operations(....)

val json  Gson().toJson(operation)

val multiOperations:MultiOperations Gson().fromJson(json,

Answered By – Zulqarnain

Leave a Comment