Reputation: 87
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
error:
Upvotes: 3
Views: 18415
Reputation: 651
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)
Upvotes: 2
Reputation: 10625
Either you can use -
var inlit = multiOperations1() as Operations
You can typecast your derived class to parent class. In your case multiOperations1
class have a parent class Operations
.
Just a suggestion start you class name like multiOperations1
from capital letter.
Upvotes: 0
Reputation: 89548
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.
Upvotes: 3