https://kotlinlang.org logo
#announcements
Title
# announcements
m

Marko Novakovic

03/31/2021, 7:24 AM
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

Tomasz Krakowiak

03/31/2021, 7:38 AM
@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

Marko Novakovic

03/31/2021, 7:41 AM
@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

Tomasz Krakowiak

03/31/2021, 7:47 AM
@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

Marko Novakovic

03/31/2021, 7:53 AM
true 😄
3 Views