Skip to content

Commit

Permalink
HList_apply_Idx (#2967)
Browse files Browse the repository at this point in the history
  • Loading branch information
mergify[bot] committed Jun 4, 2024
2 parents 1ceae3d + 101af80 commit dce2d04
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,15 @@ package slick.test.collection.heterogeneous
import org.junit.Test
import org.junit.Assert._
import slick.collection.heterogeneous.*
import org.w3c.dom.Text

import scala.util.*

class HListTest {

val hl1 = "test" :: HNil
val hl2 = 1 :: "test2" :: HNil

val c = hl1 ::: hl2
val cc = c ::: c
val cc = c ::: c

@Test
def concatTest: Unit = {
Expand Down Expand Up @@ -49,4 +48,29 @@ class HListTest {

}

@Test
def idx: Unit = {

assert(Try(HNil(0)).isFailure)

assert(hl1(0) == hl1.head)

assert(Try(hl1(-1)).isFailure)

assert(Try(hl1(1)).isFailure)

assert(hl2(0) == hl2.head)

assert(hl2(1) == hl2.tail.head)

assert(c(0) == c.head)

assert(c(1) == c.tail.head)

assert(c(2) == c.tail.tail.head)

assert(Try(c(3)).isFailure)
}


}
13 changes: 13 additions & 0 deletions slick/src/main/scala/slick/collection/heterogeneous/HList.scala
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,19 @@ sealed abstract class HList extends Product {
i
}

def apply(idx: Int): Any = {
require(idx >= 0, "Index should be non negative")
var i = 0
var h = this
while(h.nonEmpty && i < idx) {
i += 1
h = h.tail
}
if(i < idx) throw new IndexOutOfBoundsException
h.head
}


/** Prepend an element to this HList, returning a new HList. */
@inline final def :: [E](elem: E): :: [E] = new HCons[E, Self](elem, this.asInstanceOf[Self])

Expand Down

0 comments on commit dce2d04

Please sign in to comment.