How val is initialised in two objects inheriting the same trait in scala? - scala

I think my question is related but not the same as this one here.
Let define my first class
case class NoteTaker() {
private var note: Seq[String] = Seq("\n")
override def toString: String = this.note.mkString("\n")
def add(newNote: String): Unit = note ++= Seq(newNote)
}
Now I have a trait
trait SilentLogger {
import scala.util.{ Failure, Success }
val notepad = NoteTaker()
def tryAndLog[X, Y](x: X, f: X => Y): Y = {
notepad.add("Run with this input: " + x.toString)
(try {
println("Before: " + notepad.toString)
val result = f(x)
println("After: " + notepad.toString)
notepad.add("Get result:-------------------------------\n" + result.toString)
println(notepad.toString)
Success(result)
} catch {
case e: Throwable => {
println(
"Exception occurs:" + "\n" +
notepad.toString + "\n" +
e.getMessage + "\n" +
e.getStackTrace.mkString("\n")
)
Failure(e)
}}).get
}
}
I intend to use this trait to mix in with any classes where I want to collect some notes and only print out the note when there is an exception. Otherwise, I maybe just save it to a log file somewhere.
I want the notepad to be created once and reused for each of the object. In fact, I don't mind if they share the same notepad. Therefore, I chose to use 'val' in my trait.
As an example, I then create a class
case class MyClass (myField : String) extends SilentLogger {
def makeAnother : MyClass = tryAndLog("makeAnother",(x: String) => {
notepad.add(x)
val result = this.copy(myField = this.myField + " addNewField " + x)
notepad.add(result.myField)
return result
})
}
And finally I try to create two objects as follow:
scala> val firstObject = MyClass("firstObject")
firstObject: MyClass = MyClass(firstObject)
scala> val secondObject = firstObject.makeAnother
Before:
Run with this input: makeAnother
Exception occurs:
Run with this input: makeAnother
makeAnother
firstObject addNewField makeAnother
null
secondObject: MyClass = MyClass(firstObject addNewField makeAnother)
I'm really confused here. Obviously an exception occurred. But the secondObject was created just fine? But the logging message get printed out on stdout with the error 'null'.
I think my question is whether my first and second objects are actually using the same notepad or separate? How are the initialisation and the scope of notepad defined here? Is there something wrong with the way I use 'Try'?

This is caused of anonymous function with explicitly return:
(x: String) => {
notepad.add(x)
val result = this.copy(myField = this.myField + " addNewField " + x)
notepad.add(result.myField)
return result
}
In Scala, when explicitly declare return in anonymous function, it will throw NonLocalReturnControl, this will skip the later code block execute, since you have catched the Throwable, so it also will go to your catch code block.
So maybe you can remove return directly to solve this issue.

Related

Scala Error Import

I'm learning Scala, and I was attempting to import from 2 scrips in different classes, but, I get an error, and I don't know why.
This class, in Summer.scala, is where I try to import the singleton object from class ChecksumAccumulator.
import ChecksumAccumulator.calculate
object Summer{
def main(args: Array[String]): Unit= {
for (arg <- args)
println(arg + " : " + calculate(arg))
}
}
Class ChecksumAccumulator, with the singleton object ChecksumAccumulator.
object ChecksumAccumulator {
/*
When a singleton object shares the same name
with a class, it is called that class's companion object.
*/
private val cache = mutable.Map.empty[String, Int]
def calculate(s: String): Int =
if (cache.contains(s))
cache(s)
else {
val acc = new ChecksumAccumulator
//The object with the same name of the class can acces to the private members.
//println(acc.sum)
for (c <- s)
acc.add(c.toByte)
val cs = acc.checksum()
cache += (s -> cs)
cs
}
def showMap() : Unit = {
for(base:String <- cache.keys)
println(cache(base))
}
//def showMap(): String = { var cadena = cache("Every value is an object.") + " "+ cache("Every value is an object. per second time!!"); cadena }
}
This script throw this mistake
scala Summer.scala
Summer.scala:8: error: not found: object ChecksumAccumulator import
ChecksumAccumulator.calculate ^ Summer.scala:14: error: not found:
value calculate println(arg + " : " + calculate(arg)) ^ two errors
found
It seems like it's a duplicated question, but I can't yet mark questions as duplicated nor comment on them.
If that is all your code, it means you're missing:
class ChecksumAccumulator { ... }
Because you're trying to create an instance of this class:
val acc = new ChecksumAccumulator
And it's impossible to achieve with just:
object ChecksumAccumulator { ... }
Check out this answer about exactly the same code example. There is the missing definition of class ChecksumAccumulator :
https://stackoverflow.com/a/8681616/5100014
Just make sure to paste it into the same file with object ChecksumAccumulator

Use of break in Scala With Return Value

I have the below requirement where I am checking whether a value is greater than 10 or not and based on that I will break, otherwise I will return a String. Below is my code:
import scala.util.control.Breaks._
class BreakInScala {
val breakException = new RuntimeException("Break happened")
def break = throw breakException
def callMyFunc(x: Int): String = breakable(myFunc(x))
def myFunc(x: Int): String = {
if (x > 10) {
"I am fine"
} else {
break
}
}
}
Now what is the happening is that I am getting the error message saying "type mismatch; found : Unit required: String" The reason is :
def breakable(op: => Unit)
But then how I will write a function which can return value as well as break if required?
The Scala compiler can evaluate that a branch throws an exception and not use it to form a minimum bound for the return type, but not if you move the throwing code out in a method: since it can be overridden, the compiler cannot be sure it will actually never return.
Your usage of the Break constructs seems confused: it already provides a break method, there is no need to provide your own, unless you want to throw your exception instead, which would make using Break unnecessary.
You are left with a couple of options then, since I believe usage of Break is unnecessary in your case.
1) Simply throw an exception on failure
def myFunc(x: Int): String = {
if (x > 10) {
"I am fine"
} else {
throw new RuntimeException("Break happened")
}
}
def usemyFunc(): Unit = {
try {
println("myFunc(11) is " + myFunc(11))
println("myFunc(5) is " + myFunc(5))
} catch {
case e: Throwable => println("myFunc failed with " + e)
}
}
2) Use the Try class (available from Scala 2.10) to return either a value or an exception. This differs from the previous suggestion because it forces the caller to inspect the result and check whether a value is available or not, but makes using the result a bit more cumbersome
import scala.util.Try
def myFunc(x: Int): Try[String] = {
Try {
if (x > 10) {
"I am fine"
} else {
throw new RuntimeException("Break happened")
}
}
}
def useMyFunc(): Unit = {
myFunc match {
case Try.Success(s) => println("myFunc succeded with " + s)
case Try.Failure(e) => println("myFunc failed with " + e)
}
}
3) If the thrown exception isn't relevant, you can use the Option class instead.
You can see how the multiple ways of working with Options relate to each other in
this great cheat sheet.
def myFunc(x: Int): Option[String] = {
if (x > 10) {
Some("I am fine") /* Some(value) creates an Option containing value */
} else {
None /* None represents an Option that has no value */
}
}
/* There are multiple ways to work with Option instances.
One of them is using pattern matching. */
def useMyFunc(): Unit = {
myFunc(10) match {
case Some(s) => println("myFunc succeded with " + s)
case None => println("myFunc failed")
}
}
/* Another one is using the map, flatMap, getOrElse, etc methods.
They usually take a function as a parameter, which is only executed
if some condition is met.
map only runs the received function if the Option contains a value,
and passes said value as a parameter to it. It then takes the result
of the function application, and creates a new Option containing it.
getOrElse checks if the Option contains a value. If it does, it is returned
directly. If it does not, then the result of the function passed to it
is returned instead.
Chaining map and getOrElse is a common idiom meaning roughly 'transform the value
contained in this Option using this code, but if there is no value, return whatever
this other piece of code returns instead'.
*/
def useMyFunc2(): Unit = {
val toPrint = myFunc(10).map{ s =>
"myFunc(10) succeded with " + s
}.getOrElse{
"myFunc(10) failed"
}
/* toPrint now contains a message to be printed, depending on whether myFunc
returned a value or not. The Scala compiler is smart enough to infer that
both code paths return String, and make toPrint a String as well. */
println(toPrint)
}
This is a slightly odd way of doing things (throwing an exception), an alternative way of doing this might be to define a "partial function" (a function which is only defined only a specific subset of it's domain a bit like this:
scala> val partial = new PartialFunction[Int, String] {
| def apply(i : Int) = "some string"
| def isDefinedAt(i : Int) = i < 10
}
partial: PartialFunction[Int, String] = <function1>
Once you've defined the function, you can then "lift" it into an Option of type Int, by doing the following:
scala> val partialLifted = partial.lift
partialOpt: Int => Option[String] = <function1>
Then, if you call the function with a value outside your range, you'll get a "None" as a return value, otherwise you'll get your string return value. This makes it much easier to apply flatMaps/ getOrElse logic to the function without having to throw exceptions all over the place...
scala> partialLifted(45)
res7: Option[String] = None
scala> partialLifted(10)
res8: Option[String] = Some(return string)
IMO, this is a slightly more functional way of doing things...hope it helps

testing if a given instance is a (sub)class of a given Class in scala

say your given an instance of List[Class[_ <: Base]], and say that many classes extends Base:
class A extends Base
class B extends Base
class C extends A
etc'...
now, the given list may contain only some classes. e.g. : val classes = classOf[A] :: Nil, well, how can i test when i get an instantiated val if it's class is of type that is found in the list, or if it a subclass for a class in the list? i.e. how would you implement:
def testClass(class : List[Class[_ <: Base]], instance : Base) : Boolean
when:
val classes = classOf[A] :: Nil
testClass(classes, new A) // should return true
testClass(classes, new B) // should return false
testClass(classes, new C) // should return true
use case:
i'm trying to write a generic retry pattern, i.e. getting some code that is very error prone, and i want to retry executing it for some number of maximum tries, when every time it fails, it should execute some "wait" method.
e.g.
retryRequest({
//Some code that throws exceptions
}, classOf[SomeException] :: classOf[SomeOtherException] :: Nil,
100, {Thread.sleep(5000)})
well this works OK, but it won't test for subclasses of a given exception:
def retryRequest(req : => Unit, validExceptions : List[Class[_ <: java.lang.Throwable]], tries : Int, waitMethod : => Unit) {
var keepTrying = false
var tryCount = 0
do{
try{
logger.debug("retryRequest, try #" + tryCount)
keepTrying = false
req
}catch{
case ex if(tryCount >= tries && validExceptions.contains(ex.getClass)) => {
throw new MaxTriesReachedException("tried for " + tryCount + "times, but no luck. " +
"you may want to try ommitting generic exceptions types from the given list.")
}
case ex if (validExceptions.contains(ex.getClass)) => {
logger.debug("intercepted " + ex.toString)
tryCount += 1
keepTrying = true
waitMethod
}
}
}while(keepTrying)
}
i would realy want to replace:
validExceptions.contains(ex.getClass)
with something like:
validExceptions.exists(exClass => ex.isInstanceOf[exClass]) //won't compile
is it possible? how?
A simpler way would be to use util.control.Exception:
def retryRequest(req: => Unit,
validExceptions: List[Class[_ <: Throwable]],
tries: Int,
waitMethod: => Unit): Unit =
(Exception.catching(validExceptions:_*) withApply { e =>
waitMethod
if (tries > 1) retryRequest(req, validExceptions, tries - 1, waitMethod)
}) { req }
retryRequest( { println("a"); throw new Exception },
List(classOf[Exception]),
3,
Thread.sleep(100))
In short: withApply takes a closure that handles the case when one of the exceptions passed to catching is thrown. In our case, we simply call ourselves recursively (given that the number of retries is small, I don't think this is a problem).
I think this should work:
validExceptions.exists(exClass => exClass.isAssignableFrom(ex.getClass))
http://docs.oracle.com/javase/6/docs/api/java/lang/Class.html#isAssignableFrom%28java.lang.Class%29

Scala DSL - implicit methods of a function object

In my DSL I want to be able to do like this:
val a = 5
Parse("TYPE") {
a match {
case 3 => info("almost")
case s: String => error("wrong type")
case 5 => info("you won!")
case _ => error("omg")
}
}
with output
[INFO] TYPE: you won!
where Parse is a function object, which has the apply(String), info(String) and error(String) methods:
object Parse {
def apply(name: String)(parseF: => Unit) { parseF }
def info(text: String) { println("[INFO] " + name + ": " + text) }
def error(text: String) { println("[ERROR] " + name + ": " + text) }
}
The trick is that the output of the info and error methods should be somehow native to the Parse object and construct the message by the example as shown above. Therefore, they
have to be accessible like in the example, without any imports.
have to have the access to the first argument passed to Parse() ("TYPE" in the example).
must not create any instances or extra objects during their working.
This is an ideal description. I think that it will require some more boilerplate. Please suggest, how can I acheive that?
EDIT: my initial guess to declare the info and error methods inside the apply method does not make them visible in the parseF method being passed. Well, unsurprisingly..
Maybe something like this:
object Parse {
val currentName = new util.DynamicVariable("<none>")
def apply(name: String)(parseF: => Unit) = currentName.withValue(name)(parseF)
def info(text: String) = println("[INFO] %s: %s" format (currentName.value, text)
}
// usage
import Parse._ // there's no other way to get ability to call 'info' without 'Parse'.
Parse("TYPE") {
// some code
info("some info") // prints: [INFO] TYPE: some info
}
info("some other info") // prints: [INFO] <none>: some other info
If needed, it's easy to make info throw exception if it is called outside Parse {} block.
There is no solution that satisfies 1-3. You can have 1 and 2 or 2 and 3 with slightly different syntax.
1 and 2)
class Parse(val s:String) {
def info....
}
new Parse("TYPE") {
}
2 and 3)
object Parse {
def apply(s:String)(f:String=>Unit) = ...
}
Parse("TYPE")(s => {
})

Mixing in a trait dynamically

Having a trait
trait Persisted {
def id: Long
}
how do I implement a method that accepts an instance of any case class and returns its copy with the trait mixed in?
The signature of the method looks like:
def toPersisted[T](instance: T, id: Long): T with Persisted
This can be done with macros (that are officially a part of Scala since 2.10.0-M3). Here's a gist example of what you are looking for.
1) My macro generates a local class that inherits from the provided case class and Persisted, much like new T with Persisted would do. Then it caches its argument (to prevent multiple evaluations) and creates an instance of the created class.
2) How did I know what trees to generate? I have a simple app, parse.exe that prints the AST that results from parsing input code. So I just invoked parse class Person$Persisted1(first: String, last: String) extends Person(first, last) with Persisted, noted the output and reproduced it in my macro. parse.exe is a wrapper for scalac -Xprint:parser -Yshow-trees -Ystop-after:parser. There are different ways to explore ASTs, read more in "Metaprogramming in Scala 2.10".
3) Macro expansions can be sanity-checked if you provide -Ymacro-debug-lite as an argument to scalac. In that case all expansions will be printed out, and you'll be able to detect codegen errors faster.
edit. Updated the example for 2.10.0-M7
It is not possible to achieve what you want using vanilla scala. The problem is that the mixins like the following:
scala> class Foo
defined class Foo
scala> trait Bar
defined trait Bar
scala> val fooWithBar = new Foo with Bar
fooWithBar: Foo with Bar = $anon$1#10ef717
create a Foo with Bar mixed in, but it is not done at runtime. The compiler simply generates a new anonymous class:
scala> fooWithBar.getClass
res3: java.lang.Class[_ <: Foo] = class $anon$1
See Dynamic mixin in Scala - is it possible? for more info.
What you are trying to do is known as record concatenation, something that Scala's type system does not support. (Fwiw, there exist type systems - such as this and this - that provide this feature.)
I think type classes might fit your use case, but I cannot tell for sure as the question doesn't provide sufficient information on what problem you are trying to solve.
Update
You can find an up to date working solution, which utilizes a Toolboxes API of Scala 2.10.0-RC1 as part of SORM project.
The following solution is based on the Scala 2.10.0-M3 reflection API and Scala Interpreter. It dynamically creates and caches classes inheriting from the original case classes with the trait mixed in. Thanks to caching at maximum this solution should dynamically create only one class for each original case class and reuse it later.
Since the new reflection API isn't that much disclosed nor is it stable and there are no tutorials on it yet this solution may involve some stupid repitative actions and quirks.
The following code was tested with Scala 2.10.0-M3.
1. Persisted.scala
The trait to be mixed in. Please note that I've changed it a bit due to updates in my program
trait Persisted {
def key: String
}
2. PersistedEnabler.scala
The actual worker object
import tools.nsc.interpreter.IMain
import tools.nsc._
import reflect.mirror._
object PersistedEnabler {
def toPersisted[T <: AnyRef](instance: T, key: String)
(implicit instanceTag: TypeTag[T]): T with Persisted = {
val args = {
val valuesMap = propertyValuesMap(instance)
key ::
methodParams(constructors(instanceTag.tpe).head.typeSignature)
.map(_.name.decoded.trim)
.map(valuesMap(_))
}
persistedClass(instanceTag)
.getConstructors.head
.newInstance(args.asInstanceOf[List[Object]]: _*)
.asInstanceOf[T with Persisted]
}
private val persistedClassCache =
collection.mutable.Map[TypeTag[_], Class[_]]()
private def persistedClass[T](tag: TypeTag[T]): Class[T with Persisted] = {
if (persistedClassCache.contains(tag))
persistedClassCache(tag).asInstanceOf[Class[T with Persisted]]
else {
val name = generateName()
val code = {
val sourceParams =
methodParams(constructors(tag.tpe).head.typeSignature)
val newParamsList = {
def paramDeclaration(s: Symbol): String =
s.name.decoded + ": " + s.typeSignature.toString
"val key: String" :: sourceParams.map(paramDeclaration) mkString ", "
}
val sourceParamsList =
sourceParams.map(_.name.decoded).mkString(", ")
val copyMethodParamsList =
sourceParams.map(s => s.name.decoded + ": " + s.typeSignature.toString + " = " + s.name.decoded).mkString(", ")
val copyInstantiationParamsList =
"key" :: sourceParams.map(_.name.decoded) mkString ", "
"""
class """ + name + """(""" + newParamsList + """)
extends """ + tag.sym.fullName + """(""" + sourceParamsList + """)
with """ + typeTag[Persisted].sym.fullName + """ {
override def copy(""" + copyMethodParamsList + """) =
new """ + name + """(""" + copyInstantiationParamsList + """)
}
"""
}
interpreter.compileString(code)
val c =
interpreter.classLoader.findClass(name)
.asInstanceOf[Class[T with Persisted]]
interpreter.reset()
persistedClassCache(tag) = c
c
}
}
private lazy val interpreter = {
val settings = new Settings()
settings.usejavacp.value = true
new IMain(settings, new NewLinePrintWriter(new ConsoleWriter, true))
}
private var generateNameCounter = 0l
private def generateName() = synchronized {
generateNameCounter += 1
"PersistedAnonymous" + generateNameCounter.toString
}
// REFLECTION HELPERS
private def propertyNames(t: Type) =
t.members.filter(m => !m.isMethod && m.isTerm).map(_.name.decoded.trim)
private def propertyValuesMap[T <: AnyRef](instance: T) = {
val t = typeOfInstance(instance)
propertyNames(t)
.map(n => n -> invoke(instance, t.member(newTermName(n)))())
.toMap
}
private type MethodType = {def params: List[Symbol]; def resultType: Type}
private def methodParams(t: Type): List[Symbol] =
t.asInstanceOf[MethodType].params
private def methodResultType(t: Type): Type =
t.asInstanceOf[MethodType].resultType
private def constructors(t: Type): Iterable[Symbol] =
t.members.filter(_.kind == "constructor")
private def fullyQualifiedName(s: Symbol): String = {
def symbolsTree(s: Symbol): List[Symbol] =
if (s.enclosingTopLevelClass != s)
s :: symbolsTree(s.enclosingTopLevelClass)
else if (s.enclosingPackageClass != s)
s :: symbolsTree(s.enclosingPackageClass)
else
Nil
symbolsTree(s)
.reverseMap(_.name.decoded)
.drop(1)
.mkString(".")
}
}
3. Sandbox.scala
The test app
import PersistedEnabler._
object Sandbox extends App {
case class Artist(name: String, genres: Set[Genre])
case class Genre(name: String)
val artist = Artist("Nirvana", Set(Genre("rock"), Genre("grunge")))
val persisted = toPersisted(artist, "some-key")
assert(persisted.isInstanceOf[Persisted])
assert(persisted.isInstanceOf[Artist])
assert(persisted.key == "some-key")
assert(persisted.name == "Nirvana")
assert(persisted == artist) // an interesting and useful effect
val copy = persisted.copy(name = "Puddle of Mudd")
assert(copy.isInstanceOf[Persisted])
assert(copy.isInstanceOf[Artist])
// the only problem: compiler thinks that `copy` does not implement `Persisted`, so to access `key` we have to specify it manually:
assert(copy.asInstanceOf[Artist with Persisted].key == "some-key")
assert(copy.name == "Puddle of Mudd")
assert(copy != persisted)
}
While it's not possible to compose an object AFTER it's creation, you can have very wide tests to determine if the object is of a specific composition using type aliases and definition structs:
type Persisted = { def id: Long }
class Person {
def id: Long = 5
def name = "dude"
}
def persist(obj: Persisted) = {
obj.id
}
persist(new Person)
Any object with a def id:Long will qualify as Persisted.
Achieving what I THINK you are trying to do is possible with implicit conversions:
object Persistable {
type Compatible = { def id: Long }
implicit def obj2persistable(obj: Compatible) = new Persistable(obj)
}
class Persistable(val obj: Persistable.Compatible) {
def persist() = println("Persisting: " + obj.id)
}
import Persistable.obj2persistable
new Person().persist()