Scala weird printing out toString() override - scala

class Complex(real: Double, imaginary: Double) {
def re = real
def im = imaginary
override def toString() : String =
"" + re + (if (im < 0) "" else "+") + im + "i"
}
object Runme {
// making a new starting point...
def main(args: Array[String]): Unit = {
var c = new Complex(2.3, 4.5)
print(c)
}
}
When I run this code, why do I get "Complex#3834d63f" instead of "2.3+4.5i"?

I had accidentally nested the class Complex declaration inside another class Complex declaration. This question is now resolved.

Related

Scala - error: illegal start of statement (no modifiers allowed here)

Why do I get the error
error: illegal start of statement (no modifiers allowed here)
override def toString = {
^
when loading the following code (wrapped in a .scala file) from spark-shell (Spark version 2.2.0, Scala version 2.11.8)?
import org.apache.spark.util.StatCounter
class NAStatCounter extends Serializable
{
val stats: StatCounter = new StatCounter()
var missing: Long = 0
def add(x: Double): NAStatCounter = {
if (java.lang.Double.isNaN(x)) {
missing += 1
} else {
stats.merge(x)
}
this
}
def merge(other: NAStatCounter): NAStatCounter = {
stats.merge(other.stats)
missing += other.missing
this
}
override def toString = {
"stats: " + stats.toString + " NaN: " + missing
}
}
object NAStatCounter extends Serializable {
def apply(x: Double) = new NAStatCounter().add(x)
}
It is an example code from a book and it looks weird I get this error...
toString method returns a String so just add return type to it.
override def toString: String = {
"stats: " + stats.toString + " NaN: " + missing
}

Creating Singleton Object from a class in Scala

When I was playing with the Scala, I couldn't figure out something. Maybe I am doing completely wrong.
I was trying with Rational Example and Complex Example but I couldn't find a way to use operations like R*3/5 and 1/2*R
here is the complex numbers example I am working on
class Complex(val real : Int, val img : Int){
def this(real: Int) = this(real, 0)
def *(that : Complex) = {
val realPart = this.real * that.real + -(this.img * that.img)
val imgPart = this.real * that.img + this.img * that.real
new Complex(realPart, imgPart)
}
override def toString = this.real + "+" + this.img + "i"
}
object Complex {
def apply(real : Int, img : Int) = new Complex(real, img)
def apply(real : Int) = new Complex(real)
}
object ComplexNumbers {
def main(args: Array[String]) {
import ComplexConversions._
println(Complex(1,2)) // 1+2i
println(I*2) //0+2i
println(2*I) //0+2i
}
}
Well I have tried to create an object I
object I{
def apply() = new Complex(0,1)
def *(that : Complex) = {
val realPart = 0 * that.real + -(1 * that.img)
val imgPart = 0 * that.img + 1 * that.real
new Complex(realPart, imgPart)
}
}
but it did work for the I*2. but I have problems for 2*I. How can I reach the result that I want?
When you call "I * 2", scala looks for a method named "*" on the class of I, and finds it.
When you call "2 * I", scala looks for a method named "*" on the class of 2 (which is Int), and cannot find one.
Even though Int is defined externally, you can add this method to it in Scala via the "implicit conversion" mechanism. This is covered briefly in the "implicits" example and in more detail elsewhere, e.g. here
Try adding some code like the following to your "Complex" object:
object Complex {
implicit class IntOps(x: Int) {
def *(y: Complex) = y * x
}
}
You'll also need to declare I as a val, rather than an Object for this to work:
val I = Complex(0, 1)
(or add an implicit method like class Complex { def *(i: I) = ... }, but that's much uglier)
(I assume by Complex Example, you mean this?)
Working code:
class Complex(val real : Int, val img : Int){
def this(real: Int) = this(real, 0)
def *(that : Complex) = {
val realPart = this.real * that.real + -(this.img * that.img)
val imgPart = this.real * that.img + this.img * that.real
new Complex(realPart, imgPart)
}
override def toString = this.real + "+" + this.img + "i"
}
object Complex {
def apply(real : Int, img : Int) = new Complex(real, img)
def apply(real : Int) = new Complex(real)
val I = Complex(0, 1)
implicit def toComplex(x: Int): Complex = new Complex(x)
}
object ComplexNumbers {
def main(args: Array[String]) {
import Complex._
println(Complex(1,2)) // 1+2i
println(I*2) //0+2i
println(2*I) //0+2i
}
}
If you want to be able to use 2*I, you will need to add a new * override for the Int class (since * is really a method of the class Int, meaning 2*I is really 2.*(I)).
You can accomplish this with an implicit class:
scala> case class myInt(i: Int){
| def mult(that: Int): myInt = myInt(that * i)
| }
defined class myInt
scala> implicit class intOverride(i: Int){
| def *(that: myInt): myInt = that.mult(i)
| }
defined class intOverride
scala> val a = myInt(2)
a: myInt = myInt(2)
scala> 2 * a
res1: myInt = myInt(4)

Get value directly or via method in Scala?

One is able to define methods without paranthesis if they have no arguments. A special use-case is to use this to get values. Should I do this, or rather directly get the value?
So
class Complex(real: Double, imaginary: Double) {
def re = real
def im = imaginary
override def toString() =
"" + re + (if (im < 0) "" else "+") + im + "i"
}
or
class Complex(real: Double, imaginary: Double) {
val re = real
val im = imaginary
override def toString() =
"" + re + (if (im < 0) "" else "+") + im + "i"
}
You can put val in front of the constructor arguments to make it a bit shorter, which is effectively the same as your second piece of code:
class Complex(val re: Double, val im: Double) {
override def toString() = "" + re + (if (im < 0) "" else "+") + im + "i"
}
Note that def defines a method, while val defines a final member variable. Since the return value of these two methods is fixed, there's not really a reason to make them methods. So, in this case, use val instead of def.
Even better: make it a case class:
case class Complex(re: Double, im: Double) {
override def toString() = "%f%+fi".format(re,im)
}
This gives you re and im as members, plus some additional perks, such as copy:
val a = Complex(1,2)
val realA = a.copy(im = 0)
and unapply:
def isImaginary(a: Complex) = a match {
case Complex(0, _) => true
case _ => false
}
def abs(a: Complex) = a match {
case Complex(re, im) => re*re + im*im
}
and also equals, hashCode, etc.

Unable to println in scala program

Following scala code shows no output please help me with corrections.I'm new to scala.I am trying to print a Rational class instance.
object Test{
def main() {
var r = new Rational(2,3)
println(r)
println("Hello")
//println(Rational(2,3).add(Rational(3,3)))
}
}
class Rational(n:Int,d:Int)
{
val num:Int =n
val den:Int =d
val sum :Int =num+den
def add(that:Rational):Rational={
return new Rational(num*that.den+den*that.num,den*that.den)
}
override def toString(): String = num + "/" + den
}
object Rational {
def apply(n:Int,d:Int)=new Rational(n,d)
}
change def main() to def main(args: Array[String]), the JVM won't recognize a main method that doesn't have the right argument type

How can I easily get a Scala case class's name?

Given:
case class FirstCC {
def name: String = ... // something that will give "FirstCC"
}
case class SecondCC extends FirstCC
val one = FirstCC()
val two = SecondCC()
How can I get "FirstCC" from one.name and "SecondCC" from two.name?
def name = this.getClass.getName
Or if you want only the name without the package:
def name = this.getClass.getSimpleName
See the documentation of java.lang.Class for more information.
You can use the property productPrefix of the case class:
case class FirstCC {
def name = productPrefix
}
case class SecondCC extends FirstCC
val one = FirstCC()
val two = SecondCC()
one.name
two.name
N.B.
If you pass to scala 2.8 extending a case class have been deprecated, and you have to not forget the left and right parent ()
class Example {
private def className[A](a: A)(implicit m: Manifest[A]) = m.toString
override def toString = className(this)
}
def name = this.getClass.getName
Here is a Scala function that generates a human-readable string from any type, recursing on type parameters:
https://gist.github.com/erikerlandson/78d8c33419055b98d701
import scala.reflect.runtime.universe._
object TypeString {
// return a human-readable type string for type argument 'T'
// typeString[Int] returns "Int"
def typeString[T :TypeTag]: String = {
def work(t: Type): String = {
t match { case TypeRef(pre, sym, args) =>
val ss = sym.toString.stripPrefix("trait ").stripPrefix("class ").stripPrefix("type ")
val as = args.map(work)
if (ss.startsWith("Function")) {
val arity = args.length - 1
"(" + (as.take(arity).mkString(",")) + ")" + "=>" + as.drop(arity).head
} else {
if (args.length <= 0) ss else (ss + "[" + as.mkString(",") + "]")
}
}
}
work(typeOf[T])
}
// get the type string of an argument:
// typeString(2) returns "Int"
def typeString[T :TypeTag](x: T): String = typeString[T]
}
def name = getClass.getSimpleName.split('$').head
This will remove the $1 appearing at the end on some classes.