So my understanding of extension functions is that...
# getting-started
j
So my understanding of extension functions is that you can add a function to an existing library as a static function. I've made this:
Copy code
fun System.currentTimeSeconds(): Long {
    return System.currentTimeMillis()/1000
 }
and yet I can't do System.currentTimeSeconds(). Am I missing a concept or can you not do extension functions on System?
d
That will only work on an instance. Like
System().currentTimeSeconds()
What you need is this, to make that work.
Copy code
fun System.Companion.currentTimeSeconds(): Long {
    return System.currentTimeMillis()/1000
}
But
System
doesn't define a companion object, since it's Java nd stuff.
j
The
System()...
doesn't work because <init> is private. Why does the example used here: https://kotlinlang.org/docs/reference/extensions.html not create an instance?
s
What do you mean? All of these examples operate on instances. There is one example that operates on the companion object.
l
@Jack Englund the extension functions won’t create static functions. The function created is a normal function which can be invoked on a
instance
of the class you’re extending
a
j
I was primarily looking at the first example in that docs page.
l
val list = mutableListOf(1, 2, 3)
list.swap(0, 2) // 'this' inside 'swap()' will hold the value of 'list'
That’s exactly what we said, the
swap
function is called on an instance