CASE CLASS
I would change Anagram
to a case class
. One reason for this change is more concise object declaration, e.g:
val a = Anagram("silent")
// as opposed to ...
val b = new Anagram("inlets")
Another benefit is that wordOrigin
automatically becomes a field for any Anagram
object (this is also possible with standard class declaration by prepending val
to the front of the parameter.) These two examples don't really demonstrate the full utility of case classes
so if you'd like to learn more check out this link.
STYLE
Current Scala dogma utilizes camelCase. So I've swapped word_origin
and word_sorted
for wordSorted
and wordOrigin
. I also added a return type to your method matches
.
A QUICK NOTE ON TYPES
One of the cool things about types is that they allow you to constrain your program. For example, as your matches
method currently stands there are over twenty different collection types (of the mutable and immutable variety) that may be passed in for words
(see these inheritance graphs). Long story short, I swapped Seq
for List
.
STRING OPERATIONS
Finally, to get around calling toLowerCase
I utilized a method from StringOps called equalsIgnoreCase
which returns true
if the caller and the input String
are equal (regardless of capitalization), false otherwise. To be honest I only changed this bit to show you another possibility.
case class Anagram(wordOrigin: String) {
val wordSorted = wordOrigin.sorted
def matches(xs: List[String]): List[String] = {
xs.filter(w =>
w.sorted.equalsIgnoreCase(wordSorted) && !w.equalsIgnoreCase(wordOrigin)
)
}
}
NAMES
Whoops, one more thing. I think I would also rename your class from Anagram
to Word
or something similar and rename the method from matches
to anagrams
. That is:
case class Word(...) {
// ...
def anagrams(...) = { ... }
}