I thought typealiases were the same as the original type, just a different name.
I figure typealiases have the same references as the original type.
typealias Celsius = Double
fun Double.Companion.foo() {} // Works
fun Celsius.Companion.foo() {} // Does not work
Here, Companion
is accessible from Double
but Celsius
gives an unresolved reference error.
The extension function is declared with a prefix receiver type with method name. In the above declaration, <class_name> is a receiver type and the <method_name>() is an extension function.
To create a companion object, you need to add the companion keyword in front of the object declaration. The output of the above code is “ You are calling me :) ” This is all about the companion object in Kotlin. Hope you liked the blog and will use the concept of companion in your Android application.
They can be anywhere, but it seems to make sense to have extensions for a particular class in the same file and/or package. For example, extensions to String could be in StringExtensions. kt, and that could optionally be in an extensions package. Save this answer.
If the extension is defined at the top level of the class, it can access all the private variables and functions of that class. If the extension function is defined outside the class, it can not access the private variables or functions of that class.
No, you can't access to the companion objects via typealias. One possible workaround to create one more typealias for concrete companion:
typealias CelsiusCompanion = Double.Companion
After that you can use it as following:
fun CelsiusCompanion.foo() {}
If you want to define an extension function, it is not possible as hluhovskyi already stated, but things are differently if you just want to invoke functions of a companion object
.
There are two ways of accessing functions and properties within a companion object
. You can either specify the access explicitely or implicitely. The implicit way works with a typealias
the explicit one does not.
Consider this minimal example:
class ClassWithCompanion{
companion object {
fun sayHello() {
println("Hello")
}
}
}
typealias Alias = ClassWithCompanion
fun main(args: Array<String>) {
ClassWithCompanion.sayHello() // implicit
ClassWithCompanion.Companion.sayHello() // explicit
Alias.sayHello() // implicit (works)
Alias.Companion.test() // explicit (does not work)
}
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