Get value directly or via method in Scala? - 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.

Related

Override "operators" and println method in Scala

I need to create methods for basic operations for different types so the output of the expression: println(1 + 2*I + I*3 + 2) is 3+5i. I am new to Scala and here is what I have so far:
class IClass() {
var value = 0
def *(number: Int): String = {
//value += number
value + "i"
}
}
object ComplexNumbers {
var TotalValue: Int = 0
var TotalString: String = ""
// ...
def Complex(num1: Int, num2: Int): String ={
num1 + "+" + num2 + "i"
}
implicit class IntMultiply(private val a: Int) extends AnyVal {
def + (b: String)= {
if(b.contains("i")){
TotalValue += a
TotalString.concat(b)
}
}
def * (b: IClass) = {
//b.value += a
a + "i"
}
}
implicit class StringAdd(private val a: String) extends AnyVal {
def + (b: String): String = {
if(b.contains("i")){
}
a + "i"
}
}
def main(args: Array[String]) {
println(Complex(1,2)) // 1+2i
val I = new IClass()
println(1 + 2*I + I*3 + 2) // 3+5i
// val c = (2+3*I + 1 + 4*I) * I
// println(-c) // 7-3i
}
}
I think I am going in a wrong direction with this because by implementing these operation methods on types I get an error in the println: Type Mismach because of the Any return type where I only update fields without returning anything. Any idea how to implement this?
You should think of the complex numbers as a class with certain behaviors, and define it first, rather than focusing on the one concrete side effect you are after at the moment. It seems counter intuitive, but implementing a more abstract/general problem often makes the job easier than trying to narrow it down to just the task at hand.
case class ComplexInt(real: Int, im: Int) {
def + (other: ComplexInt) = ComplexInt(real + other.real, im + other.im)
def * (other: ComplexInt) = ComplexInt(
real * other.real - im * other.im,
real * other.im + im * other.real
)
def unary_- = ComplexInt(-real, -im)
def -(other: ComplexInt) = this + -other
override def toString() = (if(real == 0 && im != 0) "" else real.toString) + (im match {
case 0 => ""
case 1 if real == 0 => "i"
case 1 => " + i"
case n if n < 0 || real == 0 => s"${n}i"
case n => s"+${n}i"
})
}
object ComplexInt {
val I = ComplexInt(0, 1)
implicit def fromInt(n: Int) = ComplexInt(n, 0)
}
Now, you just need to import ComplexInt.I,
and then things like println(1 + 2*I + I*3 + 2) will print 3+5i etc.
You can even do (1 + 2*I)*(2 + 3*I) (evaluates to -4+7i).

Scala weird printing out toString() override

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.

How does the extractor work when the `unapply` function returns Boolean instead of Option?

I learned about extractors from the stairway book:
object Twice {
def apply(x: Int) = x * 2
def unapply(x: Int) = if(x % 2 == 0) Some(x / 2) else None
}
// outside pattern mathcing, Twice.apply(21) is called
val x = Twice(21)
x match {
// inside pattern matching, Twice.unapply(x) is called,
// the result Some(21) is matched against y,
// y gets the value 21
case Twice(y) => println(x + " is twice " + y)
case _ => println(x + " is odd.")
}
That's pretty straight forward. But today I read from some book on Play framework this code:
trait RequestExtractors extends AcceptExtractors {
//Convenient extractor allowing to apply two extractors.
object & {
def unapply(request: RequestHeader): Option[(RequestHeader, RequestHeader)] = Some((request, request))
}
}
//Define a set of extractors allowing to pattern match on the Accept HTTP header of a request
trait AcceptExtractors {
//Common extractors to check if a request accepts JSON, Html, etc.
object Accepts {
import play.api.http.MimeTypes
val Json = Accepting(MimeTypes.JSON)
val Html = Accepting(MimeTypes.HTML)
val Xml = Accepting(MimeTypes.XML)
val JavaScript = Accepting(MimeTypes.JAVASCRIPT)
}
}
//Convenient class to generate extractors checking if a given mime type matches the Accept header of a request.
case class Accepting(val mimeType: String) {
def unapply(request: RequestHeader): Boolean = request.accepts(mimeType)
def unapply(mediaRange: play.api.http.MediaRange): Boolean = mediaRange.accepts(mimeType)
}
def fooBar = Action {
implicit request =>
val xmlResponse: Node = <metadata>
<company>TinySensors</company>
<batch>md2907</batch>
</metadata>
val jsonResponse = Json.obj("metadata" -> Json.arr(
Json.obj("company" -> "TinySensors"),
Json.obj("batch" -> "md2907"))
)
render {
case Accepts.Xml() => Ok(xmlResponse)
case Accepts.Json() & Accepts.JavaScript() => Ok(jsonResponse)
}
}
How does the extractor work when the unapply function returns Boolean instead of Option? How do &, Accepts.Xml work here?
I can really tell you about the play framework, but if used in pattern matching an extractor returning a boolean signifies if the pattern matches. Thus if an extractor return true it means that the pattern matches the value. This is a good link about extractors and also covers this case:
http://danielwestheide.com/blog/2012/11/21/the-neophytes-guide-to-scala-part-1-extractors.html
Generally you use extractors for two use cases:
1) Destructing an object, which means returning one or more values which represent the state of given object
2) You can also use extractors to turn an object into an object of another kind during pattern matching. I made a small example for this case:
class Division(val number: Int) {
}
object Division {
def unapply(divider: Division): Boolean = divider.number != 0
def unapply(divider: Int): Option[Division] = if (divider != 0) Some(new Division(divider)) else None
}
val divident = 15
val divider = 5
val y = divider match {
case Division(notZero) => divident / notZero.number //notZero is of type Division
case _ => throw new IllegalArgumentException()
}
Ok, I found a way to figure this out by making a minimal example:
object Unapply {
case class DividedBy(val number: Int) {
def unapply(divider: Int): Boolean = number % divider == 0
def unapply(divider: Double): Boolean = number % divider.toInt == 0
}
val x = DividedBy(15)
// y should be true
val y = 5 match {
// case DividedBy(15)() => true
case x() => true
case _ => false
}
}
The weird thing is that when you use DividedBy(15)() (commented out above), the code won't compile.
Update:
object Unapply {
case class Division(val number: Int) {
// def unapply(divider: Int): Boolean = number % divider == 0
def unapply(divider: Int): Option[(Int, Int)] = if (number % divider == 0) Some(number/divider, 0) else None
def unapply(divider: Double): Boolean = number % divider.toInt == 0
}
object Division {
def apply(number: Int) = new Division(number)
}
val divisionOf15 = Division(15)
// y should be true
val y = 5 match {
// case DividedBy(15)() => true
case divisionOf15(z, w) => s"$z, $w"
case _ => s"Not divisible"
}
val z = 5.0 match {
case divisionOf15() => "Divisible"
case _ => "Not divisible"
}
}
After some reading some old notes on the stairway book now I have a clearer understanding of this. The case class is a extractor factory.

How to design function in flow style in scala

suppose I have a util object with two function
object t {
def funA(input:String,x:Int):String = "hello"*x
def funB(input:String,tail:String):String = input + ":" + tail
}
if i run
funB(funA("x",3),"tail")
I get the result = xxx:tail
the question is how to design these two function then I can call them in a flow style like:
"x" funA(3) funB("tail")
Extend String, Using implicit class,
implicit class CustomString(str: String) {
def funcA(count:Int) = str * count
def funB(tail:String):String = str + ":" + tail
}
println("x".funcA(3).funB("tail"))
With a case class with a String field (corresponding to the original functions first argument),
case class StringOps(s: String) {
def funA(x:Int):String = s*x
def funB(tail:String):String = s + ":" + tail
}
and an implicit for converting String to StringOps,
implicit def String2StringOps(s: String) = StringOps(s)
you can enable the following usage,
scala> "hello" funA 3
hellohellohello
scala> "hello" funA 3 funB "tail"
hellohellohello:tail

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.