kol
is a collection package based on Go 1.18+ Generics.
It provides List, Set and Sequence like Kotlin collections package.
You can operate collections with method-chaining 🔗.
Out of scope
kol
is not a complete reimplementation of the kotlin.collections and kotlin.sequences packages.
It is implemented by utilizing Go language features.
go get github.com/ichizero/kol
package main
import (
"fmt"
"github.com/ichizero/kol"
)
func main() {
seq := kol.NewSequence(1, 2, 3, 4, 5).
Filter(func(e int) bool {
return e < 3
}).
Map(func(e int) int {
return e * 2
}).
Distinct().
Drop(1).
Take(2)
fmt.Println(seq.ToSlice())
}
List backend is a slice of Go.
Set backend is a map of Go. It seems like Kotlin & Java's HashMap, but it cannot be iterated in a sorted order.
List | Set | |
---|---|---|
All | ✅ | ✅ |
Any | ✅ | ✅ |
Contains | ✅ | ✅ |
Count | ✅ | ✅ |
Distinct | ✅ | ✅ |
Filter | ✅ | ✅ |
FilterIndexed | ✅ | 🚫 |
Find | ✅ | ✅ |
ForEach | ✅ | ✅ |
ForEachIndexed | ✅ | 🚫 |
Intersect | ✅ | ✅ |
Iterator | ✅ | ✅ |
Map | ✅ | ✅ |
MapIndexed | ✅ | 🚫 |
Minus | ✅ | ✅ |
None | ✅ | ✅ |
Plus | ✅ | ✅ |
Single | ✅ | ✅ |
Subtract | ✅ | ✅ |
Union | ✅ | ✅ |
Sequence enables us to lazy evaluation of a collection. In some cases, the process is faster than list operations.
For more details, please refer to the following documents.
Sequence | |
---|---|
Distinct | ✅ |
Filter | ✅ |
Map | ✅ |
Take | ✅ |
Drop | ✅ |
Because of the Go Generics specification, Map methods in each interface cannot convert an element type. You can use MapList, MapSet and MapSequence instead.
MapList(
NewList(1, 2, 3).
Map(func(e int) int {
return e * 2
}),
func(e int) string {
return strconv.Itoa(e)
})