danielleontiev
danielleontiev

Reputation: 899

How to write method with dependent type in Scala

I am trying to understand Aux pattern in Scala.

trait Lst extends Any {
  type Item
  def get(index: Int): Item
}

object Lst {
  type Aux[I] = Lst {type Item = I}
}

Also I have some classes that override Item to Integer or String or smth else:

final case class IntLst(size: Int) extends AnyVal with Lst {type Item = Int}
final case class StrLst(size: Int) extends AnyVal with Lst {type Item = Char}

I would like to write method that can create List from IntLst or StrLst instances. I write this:

def makeList(l: Lst): List[l.Item] = (0 until l.size map l.get).toList

But it does not compile: Expected class or object definition

So, how definition of makeList should look?

Full code:

import Lst.Aux

object Main {
  def main(args: Array[String]) = {

  }

  def makeList(l: Lst): List[l.Item] = {
    (0 until l.size map l.get).toList
  }

}

object Lst {
  type Aux[I] = Lst {type Item = I}
}

trait Lst extends Any {
  type Item

  def get(index: Int): Item
}

final case class StringLst(size: Integer) extends AnyVal with Lst {
  type Item = Char

  def get(index: Int) = ???

}

Upvotes: 1

Views: 179

Answers (1)

Alec
Alec

Reputation: 32309

The issue is around get. Try this instead:

def makeList(l: Lst): List[l.Item] = (0 until l.size).map(l.get(_)).toList

Upvotes: 4

Related Questions