fork download
  1. object Main {
  2. trait T { def f: Int }
  3. case class X(val f: Int) extends T
  4. case class Y(val f: Int) extends T
  5.  
  6. /* Can we make the return type more specific with an HList? (I assume not) */
  7. def create(b: Int => Boolean, x: Int => Option[X], y: Int => Option[Y])
  8. : List[T] = {
  9.  
  10. var i = 0
  11. var ts = List[T]()
  12.  
  13. while (b(i)) {
  14. x(i).map{ts ::= _}
  15. y(i).map{ts ::= _}
  16.  
  17. i += 1
  18. }
  19.  
  20. ts
  21. }
  22.  
  23. def main(args: Array[String]) {
  24. val b = (n: Int) => n < 5
  25. val x = (n: Int) => if (n % 2 == 0) Some(X(n)) else None
  26. val y = (n: Int) => if (n % 3 == 0) Some(Y(n)) else None
  27.  
  28. val ts = create(b, x, y)
  29. println(ts) /* List(X(4), Y(3), X(2), Y(0), X(0)) */
  30.  
  31. /* Can we reconstruct static type information at runtime?
  32.   * (I am still not sure what that actually means ...)
  33.   */
  34. }
  35. }
Success #stdin #stdout 0.27s 247424KB
stdin
Standard input is empty
stdout
List(X(4), Y(3), X(2), Y(0), X(0))