Scala 案例类和列表
我对 Scala 完全陌生。现在,我正在尝试将我在标准 ML 中编写的解析器移植到 Scala,并遇到以下代码问题:
abstract class Token
case class Zero extends Token
case class At extends Token
//...
object Tokenizer {
def tokenize(seq : List[Char]) : List[Token] = seq match {
case List() => error("Empty input")
case '0' :: rest => Zero :: tokenize(rest)
case '@' :: rest => At :: tokenize(rest)
//...
}
}
在 SML 中,我不必声明 tokenize() 方法的返回类型,但似乎 Scala 需要它并且它对我提供的类型不满意(它抱怨 Zero、At 是无效类型,它们应该是 Token 类型)。请注意,我还想在解析阶段的稍后时间点对标记列表进行模式匹配。
我在网络和 stackoverflow 本身上进行了一些搜索,看看以前是否提出过类似的问题(它看起来很微不足道),但不知何故我找不到任何东西。我很确定我有一些基本错误,请随时启发我:)
I'm completely new to Scala. Right now I'm attempting port a parser I wrote in Standard ML to Scala and having an issue with the following code:
abstract class Token
case class Zero extends Token
case class At extends Token
//...
object Tokenizer {
def tokenize(seq : List[Char]) : List[Token] = seq match {
case List() => error("Empty input")
case '0' :: rest => Zero :: tokenize(rest)
case '@' :: rest => At :: tokenize(rest)
//...
}
}
In SML I wouldn't have to declare the return type of the tokenize() method but it seems Scala needs it and it is somehow not happy with the type I have provided (it complains Zero, At are invalid types and that they should be of type Token instead). Note that I also want to patten match the token list at a later point in time during the parsing phase.
I did some searching on the web and on stackoverflow itself to see if a similar question has been raised before (it looked so trivial) but somehow I couldn't find anything. I'm pretty sure I've got something basic wrong, please feel free to enlighten me :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
At
和Zero
是类,而不是对象,因此它们本身不是Token
的实例。您可以通过从case class
更改为case object
来修复代码:您需要指定函数的返回类型的原因是 Scala 的编译器无法识别递归函数的类型,您可以在此处阅读更多相关信息:为什么 Scala 需要递归函数的返回类型?
At
andZero
are classes, not objects, so they are not themselves instances ofToken
. You can fix your code by changing fromcase class
tocase object
:The reason why you need to specify the return type of the function is that Scala's compiler can't figure out the type of recursive functions, you can read more about that here: Why does Scala require a return type for recursive functions?
如果您想创建
Zero
和At
案例类的新实例,那么您应该使用apply
工厂方法来实例化它们(或new
关键字:new Zero
),像这样(在 Scala 中Zero()
等于Zero.apply()
) :如果你只写
0
(而不是Zero()
) 那么您正在使用Zero
类的伴生对象,该对象是由编译器自动创建的。If you want to create new instances of
Zero
andAt
case classes, then you should useapply
factory method to instantiate them (ornew
keyword:new Zero
), like this (in ScalaZero()
would be equal toZero.apply()
):If you write just
Zero
(and notZero()
) then you are using companion object ofZero
class, that was created automatically by compiler.