1

I am going through some exercises to get accustomed to Scala's type system. I have a helper function for running unit tests where I specify the input and expected output of a function. In this case the function I'm testing returns the first n elements of a list:

val inputs: List[TestCase[(List[Any], Int), List[Any]]] = List(
      TestCase(
        input = (List('a', 't', 'o'), 2),
        output = List('a', 't')
      ),
      TestCase(
        input = (List("Vegetable", "Fruit"), 4),
        output = List("Vegetable", "Fruit")
      ),
      TestCase(
        input = (List(3.14, 6.22, 9.5), -7),
        output = Nil
      )
    )

My question is if it is possible to specify a type parameter for this input val. That List[Any] is alright, but I want to specify somehow that the input list has the same type of elements as the output List. Something like this (doesn't work btw):

val inputs[SameType]: List[TestCase[(List[SameType], Int), List[SameType]]] = ...

I'd appreciate any suggestions. Maybe type parameters are not meant to be used with vals?

In case you're wondering why I'm not just asserting the results: it's because I have multiple implementations of the same function and I don't want to repeat the test cases for every implementation.

Stefan
  • 160
  • 6

1 Answers1

4

Consider parameterising your model like so

case class TestCase[T](input: (List[T], Int), output: List[T])

so now we can define, say,

val inputs: List[TestCase[String]] = ???

In Scala 2 value definition cannot be parameterised but a method definition can, for example

def input[T](x: List[TestCase[T]]) = ???

however Scala 3 might change that so we can write

val input = [T] => (x: List[TestCase[T]]) => ???

Another approach is to use generalised constraints, for example,

def assertEquals[A, B](input: List[A], output: List[B])(implicit ev: A =:= B) = ???

assertEquals(List(1), List("")) // error: Error: Cannot prove that Int =:= String

Consider munit for examples of generalised constraints.

Mario Galic
  • 47,285
  • 6
  • 56
  • 98