Unable to println in scala program - scala

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

Related

override a val in trait from Future

I want to override the val t from getValue which returns a Future
trait demo{
val t :String
}
class Test1 extends demo{
override val t = "abc"
}
class Test2 extends demo{
override val t = ""
private def getValue ={
Future(Option("abc"))
}
}
What you can do that kind of comes close to that is to map a future to an anonymous class extending demo:
val aDemo: Future[demo] = Future("abc").map { value =>
new demo {
override val t = value
}
}
Of course, you can do that inside a for-comprehension as well, e.g.:
for (value <- Future("abc")) yield
new demo {
override val t = value
}

Get fully qualified method name in scala macros

I use Scala macros and match Apply and I would like to get fully qualified name of the function which is called.
Examples:
println("") -> scala.Predef.println
scala.Predef.println("") -> scala.Predef.println
class Abc {
def met(): Unit = ???
}
case class X {
def met(): Unit = ???
def abc(): Abc = ???
}
val a = new Abc()
val x = new Abc()
a.met() -> Abc.met
new Abc().met() -> Abc.met
X() -> X.apply
X().met() -> X.met
x.met() -> X.met
x.abc.met() -> Abc.met
On the left side is what I have in code and on the right side after arrow is what I want to get. Is it possible? And how?
Here is the macro:
import scala.language.experimental.macros
import scala.reflect.macros.blackbox
object ExampleMacro {
final val useFullyQualifiedName = false
def methodName(param: Any): String = macro debugParameters_Impl
def debugParameters_Impl(c: blackbox.Context)(param: c.Expr[Any]): c.Expr[String] = {
import c.universe._
param.tree match {
case Apply(Select(t, TermName(methodName)), _) =>
val baseClass = t.tpe.resultType.baseClasses.head // there may be a better way than this line
val className = if (useFullyQualifiedName) baseClass.fullName else baseClass.name
c.Expr[String](Literal(Constant(className + "." + methodName)))
case _ => sys.error("Not a method call: " + show(param.tree))
}
}
}
Usage of the macro:
object Main {
def main(args: Array[String]): Unit = {
class Abc {
def met(): Unit = ???
}
case class X() {
def met(): Unit = ???
def abc(): Abc = ???
}
val a = new Abc()
val x = X()
import sk.ygor.stackoverflow.q53326545.macros.ExampleMacro.methodName
println(methodName(Main.main(Array("foo", "bar"))))
println(methodName(a.met()))
println(methodName(new Abc().met()))
println(methodName(X()))
println(methodName(X().met()))
println(methodName(x.met()))
println(methodName(x.abc().met()))
println(methodName("a".getClass))
}
}
Source code for this example contains following:
it is a multi module SBT project, because macros have to be in a separate compilation unit than classes, which use the macro
macro modules depends explicitly on libraryDependencies += "org.scala-lang" % "scala-reflect" % scalaVersion.value,

How to get out value from Scala Future onComplete/onSuccess

I have a high level structure of my code as follows. This is just an example replicating the high level structure.:-
import scala.concurrent.Future
class FutureReturnsAValue extends PersonAgeModifier {
def main(args: Array[String]) {
val jhonObj = Person("Jhon", 25)
val punishmentResult = addAgeCurse(jhonObj)
println("The punishment result for Jhonny is " + punishmentResult)
}
def addAgeCurse(person: Person): String = {
val oldAge = person.age
val futureAge = LongProcessingOpForAge(person)
futureAge.onSuccess {
newAge =>
if (newAge = oldAge + 5) {
"screw the kiddo, he aged by 5 years" // somehow return this string
}
else {
"lucky chap, the spell did not affect him" // somehow return this string
}
}
}
}
class PersonAgeModifier {
def LongProcessingOpForAge(person: Person): Future[Int] = {
Future.successful {
person.age + 5
}
}
}
case class Person
(
val name: String,
var age: Int
)
object Person {
def apply(name: String, age: Int) = new Person(name, age)
}
So my requirement is this:- I need the string from the addAgeCurse() method. Now I know some off you may suggest to pass the future value LongProcessingOpForAge() as such to main() but that is not what I want here.
Questions:
What is the cleanest way to obtain the string and pass it to main(). ( By clean , I mean something which does not involve using wait for x duration as I would like to avoid any manual intervention.)
Thanks
Maybe you're asking for:
scala> import concurrent._, ExecutionContext.Implicits._
import concurrent._
import ExecutionContext.Implicits._
scala> def f = Future(42)
f: scala.concurrent.Future[Int]
scala> def g = f.map(_ + 1)
g: scala.concurrent.Future[Int]
scala> :pa
// Entering paste mode (ctrl-D to finish)
object Main extends App {
for (i <- g) println(i)
}
// Exiting paste mode, now interpreting.
defined object Main
scala> Main main null
43
That's the easy idiom to block for your answer. The main thread won't exit until it has it. Use map to transform a future value.

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.

Dynamic trait difference from Scala 2.9 to 2.10

I have written a little snippet of code to test the Dynamic trait capabilities:
class Foo extends Dynamic {
def selectDynamic(name: String) {
println("selectDynamic: " + name)
}
def applyDynamic(name: String)(args: Any*) {
println("applyDynamic: " + name)
}
def applyDynamicNamed(name: String)(args: (String, Any)*) {
println("applyDynamicNamed: " + name)
}
def updateDynamic(name: String)(value: Any) {
println("updateDynamic: " + name)
}
}
object Test {
def main(args: Array[String]) {
val foo = new Foo
foo.bar(5) //1
foo.bar(x = 5) //2
foo.bar //3
foo.baz = 5 //4
}
}
The problem is that it wouldn't compile both in Scala 2.9 and 2.10 because of the fourth line in main:
error: reassignment to val
foo.baz = 5
If I comment this string, 2.9 would complain about the second line:
error: not found: value x
foo.bar(x = 5)
Meanwhile 2.10 would compile and the program would produce:
applyDynamic: bar
applyDynamicNamed: bar
selectDynamic: bar
So now I wonder if I'm doing something wrong (maybe miss some dependencies)? Is there a difference between Dynamic's in Scala 2.9 and 2.10? And what's wrong with the foo.baz = 5?
This is a bug: https://issues.scala-lang.org/browse/SI-5733