I'm playing around with trying to generate a sequence out of a single Long value prepended to a LongRange. This works:
val seq = buildSequence<Long> {
yield(2)
yieldAll(3L..5)
}
But trying to generalize it, I can't seem to structure an extension function that I can call successfully:
infix fun Long.join(R: LongRange): Sequence<Long> {
val start = this
return buildSequence<Long> {
yield(start)
yieldAll(R)
}
}
When I attempt to call it:
(2 join 3..5).forEach { /* do something */ }
I get
Error:(26, 20) Kotlin: Unresolved reference. None of the following candidates is applicable because of receiver type mismatch: public infix fun Long.join(R: LongRange): Sequence defined in main.kotlin
It seems as though the compiler recognizes that the signature of the function is close to what I'm trying to achieve, but I'm clearly fuzzy on what "receiver type mismatch" means.
The 'receiver type mismatch' error means that what is passed as a receiver to the extension function (i.e. what it is called on) does not correspond to the declared receiver type.
Kotlin, unlike Java, doesn't promote numbers to broader numeric types, and you have to use Long literals in your code where a Long is expected:
(2L join 3L..5).forEach { /* do something */ }
Here, using 2 as a receiver is not an option because a Long is expected. But in 3L..5 using 5 is OK because there is a Long.rangeTo overload that accepts an Int and returns a LongRange.
The only exception when there is an automatic promotion is when you assign an Int literal into a variable of another integral type and when you pass an Int literal as an argument to a function that expects another integral type (as said above, it doesn't work with receivers).
val a: Long = 5 // OK
fun f(l: Long) { }
f(5) // OK
val b = 5
val c: Long = b // Error
f(b) // Error
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With