recently I came across this article -&gt; <https:/...
# announcements
m
recently I came across this article -> https://medium.com/google-developer-experts/companion-objects-kotlins-most-unassuming-power-feature-fb5c0451fbd0 It showcases some great use-cases but it made me a bit confused For example, what really is the difference between
Copy code
fun interface Validation : (String) -> Boolean {
    companion object
}

val Validation.Companion.validateEmail
    get() = Validation { it.isNotEmpty() }

val Validation.Companion.validatePassword
    get() = Validation { it.isNotEmpty() }

val isFormValid = Validation.validateEmail("email") && Validation.validatePassword("password")
and
Copy code
typealias Validation = (String) -> Boolean

val validateEmail: Validation = { email: String -> email.isNotEmpty() }
val validatePassword: Validation = { password: String -> password.isNotEmpty() }

val isFormValid = validateEmail("email") && validatePassword("password")
What are use-cases where first one would add value over second one? Or is this just semantic difference?
you can add extensions to functions and to
typealias
shown above like the “concrete” type, type is type and functions are types too
t
@Marko Novakovic I don't think you can add extension to typealias in kotlin. Maybe you can add extension to target type referencing it via alias in extension declaration - https://pl.kotl.in/U2JIFiO6j
m
@Tomasz Krakowiak Run this:
Copy code
typealias Validation = (String) -> Boolean

val validateEmail: Validation = { email: String -> email.isNotEmpty() }
val validatePassword: Validation = { password: String -> password.isNotEmpty() }

val isFormValid = validateEmail("email") && validatePassword("password")

val <http://Validation.int|Validation.int>: Int
    get() = 1

fun Validation.test(): Unit = println("Test")

fun main() {
    validateEmail.test()
    val int = <http://validateEmail.int|validateEmail.int>
    println(int)
}
@Tomasz Krakowiak didn’t try that, interesting indeed
t
@Marko Novakovic The example was incorrect.
Should be:
Copy code
typealias Validation = (String) -> Boolean
typealias SomethingUrelated = (String) -> Boolean

fun Validation.test(): Unit {
    println("Test")
}

fun main() {
    val somethingUrelated : SomethingUrelated = TODO()
    somethingUrelated.test()
}
And this one does compile.
👌 1
Also:
Copy code
typealias Validation = (String) -> Boolean
typealias SomethingUrelated = (String) -> Boolean

fun Validation.Companion.test(): Unit { // Unresolved reference: Companion
    println("Test")
}
The things are different if you use SAM of course : )
m
true 😄