https://kotlinlang.org logo
Title
j

jw

04/04/2018, 2:09 PM
the same way you would a method with the signature
fun isWeekend(date: Date): Boolean
m

mplacona

04/04/2018, 2:17 PM
That doesn't seem to work, because isn't the isWeekend method in a different scope now? Let's say my class is as follows:
class ExtensionFunctions{
    fun Date.isWeekend() = day == 6 || day == 7
}
I won't be able to test it by just calling
isWeekend(Date())
on the class right?
d

diesieben07

04/04/2018, 2:19 PM
In this case
Date.isWeekend
is both an extension function of
Date
and a member function of
ExtensionFunctions
, so you need both receivers in scope. In a member-function of
ExtensionFunctions
you can just call
Date().isWeekend()
, outside you would need
with (instanceOfExtensionFunctions) {
    Date().isWeekend()
}
👍 1
All in all I doubt you really wanted to declare the extension function inside a class.
👍 1
m

mplacona

04/04/2018, 2:23 PM
So extension functions can be anywhere? And I will just be able to access them? I think this is the bit of knowledge I am lacking about extension functions... If I were to declarem them in a Kotlin file I should just be able to use them throughout my project? Because this sounds awesome!
d

diesieben07

04/04/2018, 2:24 PM
Yes, you can make them top-level and they will be available anywhere. Just like normal top-level functions
m

mplacona

04/04/2018, 2:26 PM
anywhere in the same file you mean? Not the whole projct right? Say I had a Kotlin file called ExtensionFunctions.kt And its contents were:
import java.util.*

fun main(args: Array<String>) {
    fun Date.isWeekend() = day == 6 || day == 7
}
d

diesieben07

04/04/2018, 2:26 PM
That's inside another function, that would be local to the function.
If you put it top-level, it will be available globally
m

mplacona

04/04/2018, 2:27 PM
Ah! I feel silly now!
Of course you're right! Yeah... totally works
Thank you for your help! Super appreciate