Count unique characters in a String and group the counts
For the most part, there isn't much that I would change - well done!

First, minor things:


Remove the semi-colon in valid_nucleotide.
Next, you can change nucleotides.contains(_) (an anonymous function) to just nucleotides.contains (a method value).
The reuse of valid_nucleotide in count will result in any call with an invalid parameter getting an IllegalArgumentException("DNA is wrong"). I think this error would be confusing in this context.


The biggest single change I would make is to precompute the nucleotide counts. Currently, the code recomputes them each and every time either count or nucleotideCounts is called. Since code is immutable, it is only necessary to compute them once.

In a Java program, the "empty" nucleotides map could be made into a static member (rather than having a copy of it in every instance of the DNA class). The equivalent approach in Scala is to use a companion object (an object with the same class name as the class it is a companion to).

My version of your code looked like this:

object DNA {
  val nucleotides = Map('A' -&gt; 0, 'T' -&gt; 0, 'C' -&gt; 0, 'G' -&gt; 0)
}

class DNA(code: String) {

  code foreach validNucleotide

  val counts = countNucleotides()

  def nucleotideCounts(): Map[Char, Int] = counts

  def count(nucleotide: Char): Int = {
    validNucleotide(nucleotide)
    nucleotideCounts()(nucleotide)
  }

  private def countNucleotides(): Map[Char, Int] = {
    DNA.nucleotides ++ code.filter(DNA.nucleotides.contains).groupBy(identity).mapValues(_.length)
  }

  private def validNucleotide(char: Char) = {
    if (!DNA.nucleotides.contains(char)) {
      throw new IllegalArgumentException("Character not found in valid nucleotide set")
    }
  }
}