I started learning Scala, and like most functional languages, things get messy pretty quickly for a beginner.
Here I have built a wrapper class for Ints so that I can declare additional functions for the Int class. For example, I want to be able to do something like 1.isPrime, and it should call a function that tells me if the given number is prime or not.
Here is my code:
package object Arithmetic {
trait S99Int { me =>
var value: Int = 0
implicit def int2S99Int(value: Int):me.type = {
me.value = value; me
}
}
}
The above creates the implicit conversions that enable any class that conforms to the trait, to be able to declare additional functions for Ints. For example, I can now do this:
import Arithmetic._
object S99IntPrime extends S99Int {
import scala.math.{sqrt, abs}
def isPrime: Boolean = value match {
case -1|0|1 => false
case p => Stream.cons(2,
Stream.range(3, sqrt(abs(p)).toInt + 1, 2)) forall (p % _ != 0)
}
def main(args: Array[String]): Unit = {
println(args.head.toInt.isPrime)
}
}
I am mostly asking this question about the first snippet I posted. What are the advantages/disadvantages with declaring the base object like I have? Recommendations? Warnings? I just started learning Scala, so any advice will save me hours of Googling.