0

Kotlin - Generics

Kotlin, like as Java, also can have a type parameter:

class Box<T>(t: T) {
    var value = t
}

In general we need to provide the type arguments when we make an instance:

val box: Box<Int> = Box<Int>(1)

But if the parameters can be passed from the constructor arguments or by some other ways, it can be omitted:

val box = Box(1) // 1 has type Int, so the compiler knows that we are talking about Box<Int>

Generic functions

Not only classes can have type parameters, also functions can have it too. Type parameters are placed before the name of the function:

fun <T> singletonList(item: T): List<T> {
    // ...
}

or extesion function (see Kotlin - extension functions and properties) exapmple:

fun <T> T.basicToString() : String {
    // ...
}

To call a generic function, specify the type arguments at the call site after the name of the function:

val l = singletonList<Int>(1)

Generic constraints

The set of all possible types that can be substituted for a given type parameter may be restricted by generic constraints.

The most common type of constraint is an upper bound that corresponds to Java's extends keyword:

fun <T : Comparable<T>> sort(list: List<T>) {
    // ...
}

The type specified after a colon is the upper bound: only a subtype of Comparable<T> may be substituted for T. For example:

sort(listOf(1, 2, 3)) // OK. Int is a subtype of Comparable<Int>
sort(listOf(HashMap<Int, String>())) // Error: HashMap<Int, String> is not a subtype of Comparable<HashMap<Int, String>>

The default upper bound (if none specified) is Any?. Only one upper bound can be specified inside the angle brackets. If the same type parameter needs more than one upper bound, we need a separate where-clause:

fun <T> cloneWhenGreater(list: List<T>, threshold: T): List<T>
    where T : Comparable,
          T : Cloneable {
  return list.filter { it > threshold }.map { it.clone() }
}

If you are interested of it, you can try it here online. Full documentation you can find here. All news can be founded in a Kotlin blog

Be awesome, use Kotlin!kotlin_250x250.png


All rights reserved

Viblo
Hãy đăng ký một tài khoản Viblo để nhận được nhiều bài viết thú vị hơn.
Đăng kí