• +91 9723535972
  • info@interviewmaterial.com

Kotlin Interview Questions and Answers

Question - What is the operator overloading in Kotlin?

Answer -

In Kotlin, we can use the same operator to perform various tasks and this is known as operator overloading. To do so, we need to provide a member function or an extension function with a fixed name and operator keyword before the function name because normally also, when we are using some operator then under the hood some function gets called. For example, if you are writing num1+num2, then it gets converted to num1.plus(num2).

For example:

fun main() {
 val bluePen = Pen(inkColor = "Blue")
 bluePen.showInkColor()

 val blackPen = Pen(inkColor = "Black")
 blackPen.showInkColor()

 val blueBlackPen = bluePen + blackPen
 blueBlackPen.showInkColor()
}

 operator fun Pen.plus(otherPen: Pen):Pen{
 val ink = "$inkColor, ${otherPen.inkColor}"
 return Pen(inkColor = ink)
 }

 data class Pen(val inkColor:String){
 fun showInkColor(){ println(inkColor)}
 }

Comment(S)

Show all Coment

Leave a Comment




NCERT Solutions

 

Share your email for latest updates

Name:
Email:

Our partners