Programmer dictionary: Receiver type vs Receiver object
In previous part we’ve already described difference between object and type. Similar differentiation is used for receivers in extension functions. Let’s look at the example:
fun String.isBlank() = trim() == “”“Marcin”.isBlank()
In above usage “Marcin”
is an object passed to extension function. Inside this function it is called Receiver object. Receiver object is a different kind of an argument. Function defines extended type as String
, so inside this function String
is called Receiver type.
Note that correct term is Receiver type, not receiver class. It is important because extension functions are actually extensions to types, not to the classes. This is one of the big differences between methods and extension functions. Thanks to that we can define extension to nullable or generic types generated by the class:
fun String?.isNullOrBlank() = this == null || trim() == “”fun List<Long>.sum(): Long {
var sum = 0L
for(i in this) sum += i
return sum
}
This post is the tenth part of the Kotlin programmer dictionary. To stay up-to-date with new parts, just follow this medium. To stay in touch with my articles, observe me on Twitter. Key for mentioning me there is @MarcinMoskala.
In case you need some help, remember that I am open for consultation.
If you like it, remember to clap. Note that if you hold the clap button, you can leave more claps.
Here are other parts of the Kotlin programmer dictionary:
- Parameter vs Argument, Type parameter vs Type argument
- Statement vs Expression
- Function vs Method vs Procedure
- Property vs Field
- Class vs Type vs Object
- Object expression vs Object declaration
- Receiver
- Implicit receiver vs explicit receiver
- Extension receiver vs Dispatch receiver
- Function Type vs Function literal vs Lambda expression vs Anonymous function
- Higher-order function
- Function literal with receiver vs Function type with receiver
- Invariance vs Covariance vs Contravariance
- Event listener vs Event handler
- Delegation vs Composition