Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin vs Java @Overrides

As shown here, https://stackoverflow.com/a/16639438/8949356, in Java you can override the function of a declared class when it is public

But I want to know how to do this exact same code in Kotlin, I've tried a lot but haven't found anywhere something on this topic. And I could just go and do this in Java but the rest of my code is in Kotlin, plus I just can't stay with this kind of doubt; Kotlin feels like a great tool to me and want to learn it all.

like image 300
Paul S. Avatar asked Dec 23 '22 05:12

Paul S.


2 Answers

If you want to override method, Use override keyword.

Like this.

override fun addNumber(i : Int) {
  val sum = i+10
}

You must declare method that be overrided with open keyword. If you don't, You can't override it.

open fun addNumber(i : T)
like image 176
mel Avatar answered Jan 08 '23 00:01

mel


You can override functions and properties with the override keyword. Note though, that in Kotlin, classes are not extensible by default, so you have to declare the parent with open (i.e. open class MyClass()) if you want to extend it (Java classes are still extensible unless final).

like image 24
emerssso Avatar answered Jan 08 '23 01:01

emerssso