Reputation: 119
how can I use this typalias?
typealias MyHandler = (Int, String) -> Unit
I tried this but it doesn't work:
var myHandler = MyHandler(1, "2")
Upvotes: 1
Views: 3356
Reputation: 1685
Adding to theThapa and Fred, function typealiases are a way to declare the type of a function. It can be later used.
For example, the following shows a good example of how to declare it and use it:
import kotlin.test.*
import java.util.*
//define alias
typealias MyHandler = (Int, Int) -> Int
fun main(args: Array<String>) {
//define the function
val myHandler: MyHandler = {intValue, bValue ->
intValue + bValue
}
// class Foo takes MyHandler type as parameter to instantiate
class Foo(val action: MyHandler) {
val stateOne: Boolean = false
fun bar() {
if (stateOne) {
println(action.invoke(1, 45))
} else {
println(action.invoke(0, 65))
}
}
}
// instantiate Foo class along with constructor whose parameter is of type MyHandler
val f = Foo(myHandler)
f.bar()
}
Upvotes: 0
Reputation: 17095
typealias
are just an alias for the type :) in other words, it's just another name for the type.
Imagine having to write all the time (Int, String) -> Unit
. With typealias
you can define something like you did to help out and write less,i.e. instead of:
fun Foo(handler: (Int, String) -> Unit)
You can write:
fun Foo(handler: MyHandler)
They also help giving hints, meaning they can give you a way to describe types in a more contextualized way. Imagine implementing an app where in it's entire domain time is represented as an Int
. One approach we could follow is defining:
typealias Time = Int
From there on, every time you want to code something specifically with time, instead of using Int
you can provide more context to others by using Time
. This is not a new type, it's just another name for an Int
, so therefore everything that works with integers works with it too.
There's more if you want to have a look
Upvotes: 2
Reputation: 631
You are trying to instantiate a typealias and are getting interface doesn't have a constructor
error. To my understanding, typealias with function types work with three steps:
Define the typealias itself
typealias MyHandler = (Int, String) -> Unit
declare an action of that type
val myHandler: MyHandler = {intValue, stringValue ->
// do something
}
use that action, e.g.
class Foo(val action: MyHandler) {
val stateOne: Boolean = false
// ...
fun bar() {
if (stateOne) {
action.invoke(1, "One")
} else {
action.invoke(0, "notOne")
}
}
}
Upvotes: 4