This is my code:
bufferedWriter.write(Play.current.configuration.getString("play.compile.c.command").get.replace("{objectname}", registerdJobDetails.executableNm.mkString.split('.')(0)).replace("{executablename}", getExecutableFolderName(jobId) + registerdJobDetails.executableNm))
bufferedWriter.newLine()
bufferedWriter.write(Play.current.configuration.getString("play.runable.c.command").get.replace("{objectname}", registerdJobDetails.executableNm.mkString.split('.')(0)))
only the first line is getting written but the other lines is not getting written.
I am getting the error as
java.util.NoSuchElementException: None.get
Most likely is that your problem is that Play.current.configuration.getString("play.runable.c.command") Has type Option[String] and are calling the get method on Option which pretty much should never be called. The world would be a better place if this method didn't even exist. I digress.
If this call to getString returns None, then the call to get throws an exception that there is no value to get.
It seems that Play.current.configuration.getString("play.runable.c.command")is returning a None which will throw an exception when calling get.
this should never be done! Use a combination of map and getOrElse to avoid unexpected behaviour. For instance:
val runableConfig = Play.current.configuration.getString("play.runable.c.command")
val s = runableConfig.map {
case runable =>
runable.replace("{objectname}", registerdJobDetails.executableNm.mkString.split('.')(0)
}.getOrElse("NO CONFIG FOUND")
bufferedWriter.write(s)
or you can even make the bufferedWriter.write(s) inside the map.
If you are not aware, the map method executes when the Option is defined (it's a Some(x)) and ignores when the Option is a None
Note: if it's returning a None try to debug that. Verify that you have no typos and that you are reading the right configuration file
Related
If I have a JsValue, which method shall I use to get values from the JsValue: Json.fromJson, as, asOpt and validate?
It depends on the level of error handling you want.
What as, asOpt, and validate all have in common is that they will attempt to de-serialize a JsValue into the type T you specify, using whatever implicit Reads[T] can be resolved. Where they differ is how they behave, and what types they return.
Let's say we're working with a class Foo where we have an implicit Reads[Foo] already defined.
as[Foo] will simply try to convert a JsValue into a Foo, and if it fails, it will throw an exception. This is not a safe thing to do, as the only way to handle the error would be to catch the exception and deal with it, which you might not remember to do. JSON failing to map to a certain type is rarely an exceptional case, either--it happens all the time. as should be used rarely, at most.
asOpt[Foo] will try to convert a JsValue into a Foo, and if it fails, it will simply return None. If it's successful, it will return the de-serialized value wrapped in Some. This is much better than as, since you are forced to confront the failure case (unless you do something silly like call .get). The downside is, all of the errors are swallowed when converting the failure to None, so you have no idea why it failed. If you don't care, using asOpt is perfectly fine.
validate[Foo] will try to convert a JsValue into a Foo, and will always return a JsResult[Foo]. If the conversion is successful, it will be a JsSuccess[Foo] that contains the de-serialized value. If it fails, it will be a JsError that contains all of the error information such as what paths are missing and what types do not match what they are expected to be. You can use the fold method on JsResult to safely handle each case. For example:
js.validate[Foo].fold(
errors => /* Do something with the errors */ ,
foo => /* Do something with Foo */
)
Json.fromJson does the exact same thing as JsValue#validate. They both call the underlying Reads to return a JsResult.
I've made this recursive metod in Scala that returns a list made of all distinct elements of another list.
object es20 extends App{
def filledList:List[Int]=List()
#scala.annotation.tailrec
def distinct(l:List[Int]):List[Int] ={
if (l.isEmpty) filledList
if (filledList.forall(_!=l.head)) l.head::filledList
distinct(l.tail)
}
println(distinct(List(1,1,5,6,6,3,8,3))) //Should print List(1,5,6,3,8)
}
However, when I compile the code and then I run it, there's this exception:
java.util.NoSuchElementException: head of empty list
I thought that this exception was handle by the condition if (l.isEmpty).
How can I fix the code?
In Scala method returns last expression of the block. In your case you have three expressions: two if-expressions which result in unit and call to distinct, so checks will be executed every time you call distinct, no matter if the list is empty or not.
To fix it you can use if / else construct, or pattern match on input list, or make operation on headOption.
Anyway I doubt if this code correct: you trying to check something on 'filledList' which is always empty
You can fix this particular error by inserting else before the second if. However, as mentioned in the other answer, your code isn't correct, and won't work anyway, you need to rewrite it.
Also, I understand, that you are just trying to write this function as an exercise (if not, just do list.distinct), but I submit, that implementing quadratic solutions to trivially linear problems is never a good exercise to begin with.
//Below line of code works fine with the result,
//maxBSONValue: org.mongodb.scala.bson.BsonObjectId = BsonObjectId{value=572865049229f27baf82c974}
val maxBSONValue = org.mongodb.scala.bson.BsonObjectId("572865049229f27baf82c974")
//Subsequent execution of below line results in error
//error: org.mongodb.scala.bson.BsonObjectId.type does not take parameters
val minBSONValue = org.mongodb.scala.bson.BsonObjectId("572865049229f27baf82c96f")
Why BsonObjectId::apply(String) method does not work for the second time?
Instead of invoking apply() method from the BsonObjectId companion object (here), it seems to be seeing BsonObjectId as a type (defined here) and it complains that it doesn't take parameters (which is true). This is the cause of your error message. Not sure why it's happening though. Check out this question and see if you can find something useful (I didn't really dig too deep into it).
Sorry for posting as answer even though it isn't really one, but I think it could put you on the right track and I couldn't fit it into comments.
Im trying to map a JSONObject instance into an actual instance through Play Combinators. I am able to get the desrialization work correctly. The question is on the behavior of how map() works on an Option[JSONObject].
Option1:
jsonVal: Option[JSONObject] = getAsJson(input)
jsonVal.map(JSONUtil.fromJsonString(_.toString(), Blah.jsonReads))
Doesnt work, fails to compile as the _ is not resolved correctly. Compiler couldnt find the toString() on the object.
Option2:
jsonVal: Option[JSONObject] = getAsJson(input)
jsonVal.map(_.toString()).map(JSONUtil.fromJsonString(_, Blah.jsonReads))
Works !!. Can some one tell me why the Type of the default variable is not propagated when transformation is done as part of function argument?
It isn't behavior of map, it's behavior of _. It's just a shortcut for the normal function expression (in this case). In the first case you have
jsonVal.map(JSONUtil.fromJsonString(x => x.toString(), Blah.jsonReads))
which obviously doesn't work, and need to write the full version
jsonVal.map(x => JSONUtil.fromJsonString(x.toString(), Blah.jsonReads))
A common pattern I have in my code base is to define methods with Try[Unit] to indicate the method is doing something (like writing a transaction long to a SaaS REST endpoint) where there is no interesting return result and I want to capture any and emit any errors encountered to stdout. I have read on another StackOverflow thread this is entirely acceptable (also see 2nd comment on the question).
I am specifically and explicitly avoiding actually throwing and catching an exception which is an extraordinarily expensive activity on most JVM implementations. This means any answer which uses the Try() idiom won't help resolve my issue.
I have the following code (vastly simplified from my real life scenario):
def someMethod(transactionToLog: String): Try[Unit] = {
val result =
for {
_ <- callToSomeMethodReturningATryInstance
} yield Unit
result match {
case Success(_)
//Unit
case Failure(e) ->
println(s"oopsie - ${e.getMessage}")
}
result
}
Sometimes this code compiles just fine. Sometimes it doesn't. When it doesn't, it gives me the following compilation error:
Error:(row, col) type mismatch;
found : scala.util.Try[Unit.type]
required: scala.util.Try[Unit]
result
^
Sometimes the IntelliJ syntax highlighter shows the code as fine. Other times it shows an error (roughly the same as the one above). And sometimes I get the compiler error but not a highligher error. And other times it compiles fine and I get only a highlighter error. And thus far, I am having a difficult time finding a perfect "example" to capture the compiler error.
I attempted to "cure" the issue by adding .asInstanceOf[Unit] to the result of the for comprehension. That got it past the compiler. However, now I am getting a runtime exception of java.lang.ClassCastException: scala.Unit$ cannot be cast to scala.runtime.BoxedUnit. Naturally, this is infinitely worse than the original compilation error.
So, two questions:
Assuming Try[Unit] isn't valid, what is the Scala idiomatic (or even just preferred) way to specify a Try which returns no useful Success result?
Assuming Try[Unit] is valid, how do I get past the compilation error (described above)?
SIDENOTE:
I must have hit this problem a year ago and didn't remember the details. I created the solution below which I have all over my code bases. However, recently I started using Future[Unit] in a number of places. And when I first tried Try[Unit], it appeared to work. However, the number of times it is now causing both compilation and IDE highlighting issues has grown quite a bit. So, I want to make a final decision about how to proceed which is consistent with whatever exists (or is even emerging) and is Scala idiomatic.
package org.scalaolio.util
/** This package object serves to ease Scala interactions with mutating
* methods.
*/
package object Try_ {
/** Placeholder type for when a mutator method does not intend to
* return anything with a Success, but needs to be able to return a
* Failure with an unthrown Exception.
*/
sealed case class CompletedNoException private[Try_] ()
/** Placeholder instance for when a mutator method needs to indicate
* success via Success(completedNoExceptionSingleton)
*/
val completedNoExceptionSingleton = new CompletedNoException()
}
Replace yield Unit with yield ().
Unit is a type - () is a value (and the only possible value) of type Unit.
That is why for { _ <- expr } yield Unit results in a Try[Unit.type], just as yield String would result in a Try[String.type].