1

I would like to create a class that only holds single-digit numbers.

class onlyLikesSingleDigits(val anyNumber: Seq[Int]) {
  val onlySingleDigits = anyNumber.filter(_ < 10)
}

The idea is you can construct it, and any numbers greater than or equal to 10 that you pass into the constructor would just be discarded.

My implementation looks rather ugly. Can't I do this without using anyNumber? I want to initialize my class using the constructor parameters as input to the filter, not as actual members of the class.

How can I do this with only a single val?

2
  • if you want only filtered elements, why not use filtered sequence as constructor argument directly? the example is a bit artificial. Commented Sep 30, 2014 at 23:27
  • @Ashalynd How would I do that? Commented Oct 1, 2014 at 1:16

2 Answers 2

2

Just remove val from anyNumber and it won't be member of the class. Maybe you'll find this helpful: scala class constructor parameters

Sign up to request clarification or add additional context in comments.

Comments

1

You should better separate the data representation from constructor logic by using Factory pattern.

Data representation

scala> case class OnlyLikesSingleDigits(digits: Seq[Int])

Factory

object DigitsMaker { 
  def apply(anyNums: Seq[Int]) = OnlyLikesSingleDigits(anyNums.filter(_ < 10)) 
}

Usage

scala> val r = DigitsMaker(Seq(4, 12, 5, 76))
r: OnlyLikesSingleDigits = OnlyLikesSingleDigits(List(4, 5))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.