I'm using Scala Worksheet in IntelliJ IDEA and sometimes I get this kind of error. For example this is my code:
def silnia(n:Int):Int=
if n==0 then 1
else if n>0 then n*silnia(n-1)
else throw new Exception(s"negative number: $n")
It compiled normally before both in IntelliJ and Terminal and I got the expected result:
def silnia(n: Int): Int
but now it doesn't and instead I get this error '(' expected but identifier found. I don't think the problem is in the code but I could be wrong. Does anyone know how to solve this problem?
Related
When inspecting this code:
def getFilmById(filmId: Long) = quote {
query[Film].filter(f => f.film_id == lift(filmId))
}
ensime shows an error in place of opening brace:
an expression of type Null is ineligible for implicit conversion
The application compiles and query is generated properly, only editor marks it as a compile error.
I'm using quill 3.1.0, ensime 2.5.1, emacs 26.2-1 scala 2.12.8.
I expect no compilation error shown in editor.
val label = Try("here_a").getOrElse("here_b")
In the case where here_a is not found, this is not falling back to here_b. Why is the .getOrElse not functioning?
Thanks #jwvh. These values are sting files paths and thus the exception is the following Exception in thread "main" java.io.FileNotFoundException:
As per Andrew James Ramirez's comment I tried this but issue persists.
Try(throw new Exception("FAIL here_a")).getOrElse("here_b")
I have also tried
Try(throw new Exception("FileNotFoundException here_a")).getOrElse("here_b")
Edit
It seems I may have oversimplified this question for SO. Some more context. The string is actually a file path. Perhaps this is making a difference?
Effectively, a json file may be found in one of two possible locations. I thus wish to try the first location and if a java.io.FileNotFoundException is returned, fall back on the second location. This is what I presently have:
val input_file = Try(throw new Exception("FAIL location_a/file_a.json")).getOrElse("location_b/file_a.json")
Edit V2
I am embarrassed to say that I found the simple error. I am running this scala code on spark and I forgot to repackage in between testing. sbt package was all that was required. :-/
I think you misunderstood Try. and .getOrElse
Definition of Try :
The Try type represents a computation that may either result in an exception, or return a successfully computed value. It's similar to, but semantically different from the scala.util.Either type.
scala> Try("here_a")
res1: scala.util.Try[String] = Success(here_a)
scala> Try("here_a").get
res2: String = here_a
scala> Try(throw new Exception("FAIL here_a")).getOrElse("here_b")
res3: String = here_b
scala>
It only fails if you throw Exception. null is still a value.
Try() returns either a Success(x) or a Failure(e), where x is the successful value returned and e is the exception that was thrown. getOrElse() unwraps the Success or supplies a default value.
If you're not getting the "OrElse" then your code isn't throwing a catchable exception.
It works as you expect it should.
$ scala
Welcome to Scala 2.11.8 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_40).
Type in expressions for evaluation. Or try :help.
scala> val label = Try(throw new RuntimeException("here_a")).getOrElse("here_b")
label: String = here_b
Please provide more context in your question if you feel this answer is insufficient.
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].
Tried compiling this example https://github.com/akka/akka/blob/master/akka-samples/akka-sample-fsm/src/main/scala/DiningHakkersOnFsm.scala#L1, using Eclipse.
Came back with
an error on the last few lines...
namely
} yield system.actorOf(Props(classOf[FSMHakker], name, chopsticks(i), chopsticks((i + 1) % 5)))
gives type mismatch; found : ClassFSMHakker required: () => 0
and hakkers.foreach(_ ! Think)
gives value ! is not a member of Nothing.
Any tips to get this to compile without errors appreciated.
You are referring to a sample from the snapshot docs, but your error message suggests that you are using a released (older) version of Akka.
It seems that using type aliases confuses the Scala type inferencer or the compiler. Indeed trying to compile
import scalaz.OptionT.optionT
type Foo[A] = Option[Option[A]]
val x: Foo[Int] = Some(Some(3))
optionT(x)
results in the strange error
java.lang.IllegalArgumentException: transpose requires all collections have the same size
Due to my limited experience with Scala, I am not sure whether I should file a bug for this, ot if this is the expected behaviour.
Is this really a bug or the expected behaviour?
Having just tested that myself that IllegalArgumentException is the compiler bailing out, which would be a bug.
I also tested this and it really seems like a bug, you should report that to the scala team. You can however fix this, by giving the compiler a hint:
val x: Foo[Int] = Some(Some(4))
val y = optionT[Option](x)
y: scalaz.OptionT[Option,Int] = OptionT(Some(Some(3)))