You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
For example, considering the following NotEmptyString class, if we would like to overload the plus operator for concatenating them, should we declare the overload as a member or as an extension function?
classNotEmptyString(privatevalvalue:String) {
init {
require(value.isNotEmpty()) { "String shouldn't be empty." }
}
/* * First case - member function. * The main advantage is that consumers don't have to import the function for using it. * We can also access declarations available only in that class.*/operatorfunplus(other:NotEmptyString): NotEmptyString=NotEmptyString(value + other.value)
overridefuntoString(): String= value
}
/* * Second case - extension function. * This the way suggested by the Kotlin API guidelines to declare a function that is not part of the "very" core API * (because this is not an override, an accessor or a property of the receiver class). * But importing this operator function when writing 'NotEmptyString + NotEmptyString' feels less convenient...*/operatorfun NotEmptyString.plus(other:NotEmptyString): NotEmptyString=NotEmptyString("$this$other")
funmain() {
val hello =NotEmptyString("hello")
val world =NotEmptyString(" world")
println(hello + world) // hello world
}
Overloading operators may be an exception that should be declared as a member function...
The text was updated successfully, but these errors were encountered:
LVMVRQUXL
added a commit
to LVMVRQUXL/LVMVRQUXL
that referenced
this issue
Feb 27, 2024
Accordingly to the section Use member and extension functions appropriately, only properties, overrides and accessors should be members. But what about operator overloads?
For example, considering the following
NotEmptyString
class, if we would like to overload theplus
operator for concatenating them, should we declare the overload as a member or as an extension function?Overloading operators may be an exception that should be declared as a member function...
The text was updated successfully, but these errors were encountered: