DEV Community

Sanjay Prajapat
Sanjay Prajapat

Posted on • Originally published at sanjayprajapat.hashnode.dev

3 2

Type Aliases in Kotlin

type alias provide alternative name for existing type. if type name is longer can be introduces shorter name , it will not introduced new types, they are equivalent to corresponding types.

data class User(
    val name:String? = null,
)

// alias for Int type and ArrayList
    typealias u = Int 
    typealias l = ArrayList<String>
fun main(){
    val users:l = ArrayList()
    users.add("Jb")
    users.add("hdshj")
    print(users)
    val x:u = 34
    print(x)
}
Enter fullscreen mode Exit fullscreen mode
// type alias for inner class 
class A {
inner class Inner
}
class B {
   inner class Inner
}
    typealias AInner = A.Inner
    typealias BInner = B.Inner
Enter fullscreen mode Exit fullscreen mode
 // provide alias for Function type 
 val lamb = { x:Int, y:Int, z:Int -> print("$x $y $z") } 

 typealias MyHandler = (Int, Int, Int) -> Unit
 fun my(f:MyHandler){
     f.invoke(20,21,22)
 }
 fun main(){
     my(lamb)
 }
Enter fullscreen mode Exit fullscreen mode
 typealias Predicate<T> = (T) -> Boolean

 fun foo(p: Predicate<Int>) = p(42)
 fun main(){
     val f1: (Int) -> Boolean = { it > 0 }    
     print(foo(f1)) // true 

     val p: Predicate<Int> = { it > 0 }
     println(listOf(1, -2).filter(p)) // [1]
 }


Enter fullscreen mode Exit fullscreen mode

Sentry mobile image

Mobile Vitals: A first step to Faster Apps

Slow startup times, UI hangs, and frozen frames frustrate users—but they’re also fixable. Mobile Vitals help you measure and understand these performance issues so you can optimize your app’s speed and responsiveness. Learn how to use them to reduce friction and improve user experience.

Read the guide →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay