如何在Scala中编写依赖类型的方法

如何在Scala中编写依赖类型的方法,scala,Scala,我试图理解Scala中的Aux模式 trait Lst extends Any { type Item def get(index: Int): Item } object Lst { type Aux[I] = Lst {type Item = I} } 此外,我还有一些类可以将Item重写为Integer、String或smth-else: final case class IntLst(size: Int) extends AnyVal with Lst {type Ite

我试图理解Scala中的Aux模式

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

object Lst {
  type Aux[I] = Lst {type Item = I}
}
此外,我还有一些类可以将Item重写为Integer、String或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}
我想写一个可以从IntLst或StrLst实例创建列表的方法。我这样写:

def makeList(l: Lst): List[l.Item] = (0 until l.size map l.get).toList
但它不编译:预期的类或对象定义

那么,makeList的定义应该是什么样子的呢

完整代码:

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) = ???

}
问题就在你身边。请尝试以下方法:

def makeList(l: Lst): List[l.Item] = (0 until l.size).map(l.get(_)).toList
问题就在你身边。请尝试以下方法:

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

你在哪里定义这个方法?在文件的顶层?这将导致您所得到的错误。将其包装在一个对象中。请提供一个完整的示例。不清楚您是如何得到此错误的,并且代码由于明显不相关的原因无法编译。@BrianMcCutchon如果我在主对象中定义它,我得到:错误:9,35具有依赖类型索引的方法:Intl.项无法转换为函数value@danielleontiev您必须为我们提供一个完整的示例来调试它。这听起来像是一个错误,不是与makeList的定义有关,而是与您如何使用它有关。@TravisBrown补充道:您在哪里定义该方法?在文件的顶层?这将导致您所得到的错误。将其包装在一个对象中。请提供一个完整的示例。不清楚您是如何得到此错误的,并且代码由于明显不相关的原因无法编译。@BrianMcCutchon如果我在主对象中定义它,我得到:错误:9,35具有依赖类型索引的方法:Intl.项无法转换为函数value@danielleontiev您必须为我们提供一个完整的示例来调试它。“这听起来像是一个错误,不是与makeList的定义有关,而是与您如何使用它有关。”TravisBrown补充道