# Generic Function

DevFeed: [Generic Function](<https://devfeed.tech/articles/generic-function-25015.md>)

Original publisher: [Read original article](<https://typealias.com/concepts/generic-function/>)

Author: author@typealias.com (Dave Leeds)

Published: 2017-09-21T02:07:39Z

Content type: article

Language: en

Sources: [Dave Leeds on Kotlin - typealias.com](<https://devfeed.tech/sources/dave-leeds-on-kotlin-typealias-com.md>)

Topics: [Type Parameter](<https://devfeed.tech/topics/type-parameter.md>), [generic programming](<https://devfeed.tech/topics/generic-programming.md>), [typesafety](<https://devfeed.tech/topics/typesafety.md>), [Type Argument](<https://devfeed.tech/topics/type-argument.md>)

Tags: [function](<https://devfeed.tech/tags/function.md>), [functions](<https://devfeed.tech/tags/functions.md>), [generic](<https://devfeed.tech/tags/generic.md>), [java](<https://devfeed.tech/tags/java.md>), [kotlin](<https://devfeed.tech/tags/kotlin.md>), [kotlin-generic-function](<https://devfeed.tech/tags/kotlin-generic-function.md>), [parameter](<https://devfeed.tech/tags/parameter.md>), [programming](<https://devfeed.tech/tags/programming.md>), [type-parameter](<https://devfeed.tech/tags/type-parameter.md>), [type-safety](<https://devfeed.tech/tags/type-safety.md>)

## AI overview

Kotlin generic functions use a type parameter declared before the function name, allowing the argument and return types to stay linked. The `middleItem` example takes a `List<T>` and returns a `T`; different call sites can use different item types while preserving the result type without casting. The excerpt says Kotlin's syntax differs slightly from Java in where the type parameter and return type are declared. An abstract argument or return type can instead suit a function that only needs polymorphic behavior, but callers then need casts when recovering a more specific type.

## Source excerpt

Overview Generic functions are functions that accept a type parameter, which allows different call sites to pass different types, without sacrificing type safety. Yeah, that's a mouthful, so let's just take a look at an example. Example Definition Here's a Kotlin generic function that returns the middle-most item out of a List: fun <T> middleItem(list: List<T>): T = list[list.size / 2] This example specifies: A type parameter of type T. This type parameter declaration goes before the name of the function, and it's written here as <T>.