Skip to content

Instantly share code, notes, and snippets.

@magdamiu
Created June 20, 2020 20:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save magdamiu/da23080c2bb542beaa79ea9f0216071e to your computer and use it in GitHub Desktop.
Save magdamiu/da23080c2bb542beaa79ea9f0216071e to your computer and use it in GitHub Desktop.
General sample code with generics in Kotlin
data class Course(val name: String)
class OddList<T>(val list: List<T>) {
fun oddItems(): List<T> {
return list.filterIndexed { index, _ -> index % 2 == 1 }
}
}
fun main() {
val listOfStrings = listOf("Kotlin", "Java", "C#")
val resultOfStrings: OddList<String> = OddList(listOfStrings)
println(resultOfStrings.oddItems())
val listOfInts = listOf(1, 7, 8, 9, 12, 45)
val resultOfInts = OddList(listOfInts)
println(resultOfInts.oddItems())
val courses = listOf(
Course("Kotlin"),
Course("Java"),
Course("C#"),
Course("PHP"),
Course("C++")
)
var resultCourses = OddList(courses).oddItems()
println(resultCourses)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment