The cast can never be succeed

12,526

Solution 1

To achieve you can use Gson and avoid boilerplate code.

var operation= Operations(....)

val json = Gson().toJson(operation)

val multiOperations:MultiOperations =Gson().fromJson(json, MultiOperations::class.java)

Solution 2

You seem to have both an Operations and an Operations1 class. Your multiOperations1 class inherits from Operations instead of Operations1, so you won't be able to cast it to Operations1 (unless Operations is a subclass of Operations1).

I assume you wanted to inherit from Operations1 instead, like this:

class multiOperations1(): Operations1() {
    ...
}

A note on conventions: class names in Kotlin usually follow Java conventions, and use upper camel case, so you should probably name your class MultiOperations1 instead.

Share:
12,526

Related videos on Youtube

Usman
Author by

Usman

Updated on June 04, 2022

Comments

  • Usman
    Usman almost 2 years

    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

    error:

    This is the error which my program through