To create a custom collection in Scala that extends the standard library collections, you’ll need to follow several steps:
1. Choose the appropriate collection type to extend.
2. Extend the chosen collection trait or class.
3. Implement the required collection methods.
4. Provide any additional functionality specific to your custom collection.
For example, let’s create a custom collection called ‘PositiveIntList‘ that stores only positive integers and extends ‘scala.collection.immutable.LinearSeq‘. We chose ‘LinearSeq‘ since our custom collection is a sequence of positive integers.
import scala.collection.immutable.LinearSeq
import scala.collection.SeqFactory
import scala.collection.mutable.ListBuffer
class PositiveIntList private (protected val underlying: List[Int]) extends LinearSeq[Int] {
override def head: Int = underlying.head
override def tail: PositiveIntList = new PositiveIntList(underlying.tail)
override def isEmpty: Boolean = underlying.isEmpty
override def last: Int = underlying.last
override def init: PositiveIntList = new PositiveIntList(underlying.init)
override def knownSize: Int = underlying.length
override def length: Int = underlying.length
def add(elem: Int): PositiveIntList = {
require(elem > 0, "Only positive integers are allowed.")
new PositiveIntList(elem :: underlying)
}
}
object PositiveIntList {
def apply(elems: Int*): PositiveIntList = {
val posIntListBuf = new ListBuffer[Int]()
for (elem <- elems) {
require(elem > 0, "Only positive integers are allowed.")
posIntListBuf.prepend(elem)
}
new PositiveIntList(posIntListBuf.toList)
}
def empty: PositiveIntList = new PositiveIntList(Nil)
}
In the above code:
- We create a private constructor to ensure that only valid instances of ‘PositiveIntList‘ can be created.
- We extend ‘LinearSeq[Int]‘ to inherit most of the collection-related functionality.
- We implement the required methods like ‘head‘, ‘tail‘, ‘isEmpty‘, ‘last‘, ‘init‘, ‘knownSize‘, and ‘length‘.
- We created a custom method ‘add‘ that adds a positive integer to the collection. It also checks if the element is positive before adding it.
- We create an ‘object PositiveIntList‘ with an ‘apply‘ method to create instances of ‘PositiveIntList‘ and an ‘empty‘ method to create an empty ‘PositiveIntList‘.
Now, we can create and use our custom ‘PositiveIntList‘ as follows:
val posIntList = PositiveIntList(1, 2, 3)
val newList = posIntList.add(4)
println(posIntList) // prints PositiveIntList(1, 2, 3)
println(newList) // prints PositiveIntList(4, 1, 2, 3)
This is a simple example of creating a custom collection in Scala by extending the standard library collections. Depending on your specific use case and requirements, you may need to adjust the implementation accordingly.