I am new to Kotlin(I have exprience with Web/JS).
I am trying to get access to below function somehow I cannot get access(not showing at all)
Assume it is inside of object SomethingUtil
and using other file and imported also
fun Int.something(num:Int): Int {
return num
}
val result = SomethingUtil.something
(not access/showing)
but when I am trying to get access without keyword Int
or Double
I have no problem
fun something(num:Int): Int {
return num
}
val result = SomethingUtil.something
but here no problem
I am trying to understand/find from offical documentation what is the meaning(it is clear this function will be Integer) but no idea what is this(I thougt it is infix seems not)
CodePudding user response:
Your extension function must be outside the scope of your class. Check this example:
class MyClass {
val value = "a"
}
fun MyClass.print() = "Value = ${this.value}"
fun main() {
println(MyClass().print()) // Value = a
}
CodePudding user response:
Adding the Int.something
means that you are "adding a function to the behaviors of" Int
. This is called an "extension function." The usage of such a function would be like 1.something(2)
. Within the curly brackets of that function, calling this
will return the Int
you called it from, or in this case, 1
.
Unfortunately, extension functions cannot be accessed outside of the class that they are defined in, but they are still useful when you need to make similar operations multiple times within the same class.
Take the following two classes for this example.
object SomethingUtil {
fun Int.something(num:Int): Int {
return this num
}
fun Int.something2(num:Int): Int {
return num
}
fun something(num:Int): Int {
return num
}
fun add(num1:Int, num2:Int):Int {
return num1.something(num2)
}
fun replace(num1:Int, num2:Int):Int {
return num1.something2(num2)
}
}
fun main() {
println(SomethingUtil.something(1)) //prints 1
println(SomethingUtil.add(4,5)) //prints 9
println(SomethingUtil.replace(3,6)) //prints 6
}
I can't access the first two functions from within the main()
method, as that would give me a compiler error. Therefore, I am only limited to accessing the other three. However, given this example, you can probably see the difference between a regular function and an extension function in this object.