Skip to content

Instantly share code, notes, and snippets.

@Audhil
Last active August 18, 2020 19:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Audhil/7cad42524125422d224c31c05a425634 to your computer and use it in GitHub Desktop.
Save Audhil/7cad42524125422d224c31c05a425634 to your computer and use it in GitHub Desktop.
kotlin operator overloading - ref: https://kotlinlang.org/docs/reference/operator-overloading.html to find allowed operators to overload
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)}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment