Scala classes and class lists

I am completely new to Scala. Right now I'm trying to use the parser port that I wrote in standard ML before Scala and had a problem 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 would not need to declare the return type of the tokenize () method, but it seems to need Scala, and it is somehow dissatisfied with the type I provided (it complains that Zero, At are invalid types and that they should be of type token instead). Note: I also want patten to match the token list at a later point in time during the parsing phase.

I did a few searches on the Internet and on stackoverflow to see if a similar question had been raised before (it looked so trivial), but for some reason I could not find anything. I am pretty sure that something is wrong with me, please feel free to enlighten me :)

+4
source share
2 answers

If you want to create new instances of the case Zero and At classes, then you must use the apply factory method to create them (or new keyword: new Zero ), for example this (in Scala Zero() will be equal to Zero.apply() ):

 case '0' :: rest => Zero() :: tokenize(rest) 

If you write only Zero (and not Zero() ), you are using a companion object of the Zero class that was automatically created by the compiler.

+8
source

At and Zero are classes, not objects, so they are not Token instances. You can fix your code by changing it from case class to case object :

 case object Zero extends Token case object At extends Token 

The reason you need to specify the return type of a function is because the Scala compiler cannot determine the type of recursive functions, you can learn more about it here: Why does Scala require a return type for recursive functions?

+9
source

All Articles