Scala: Int doesn't take parameters on a recursive call - scala

I get a weird compilation error in the small Scala exercise I am working on.
I have this method that is supposed to keep on asking user input until a correct answer is provided. Alas I am stumbled at the first case in my pattern matching:
override def guess(guess: Int):Unit = {
val guessIndex = binary(array, guess)
guessIndex match {
case -1 => {
val nextAttempt = StdIn.readLine(s"Please be attentive $guess is outside the search range"
+" (0 to $upperBound). Try again: \n");
val a = validateType[Int](nextAttempt)
guess(a)
}
}
}
The IDE underlines guess(a) with the error "Int doesn't take parameters". Running sbt compile from the console confirms this error:
> compile
[info] Compiling 2 Scala sources to /home/vgorcinschi/Documents/eclipseProjects/Algorithms/Chapter 1 Fundamentals/algorithms1_4_34/target/scala-2.12/classes...
[error] /home/vgorcinschi/Documents/eclipseProjects/Algorithms/Chapter 1 Fundamentals/algorithms1_4_34/src/main/scala/ca/vgorcinschi/algorithms1_4_34/hotandcold/HotAndColdImpl.scala:23: Int does not take parameters
[error] guess(a)
[error] ^
[error] one error found
[error] (compile:compileIncremental) Compilation failed
[error] Total time: 0 s, completed 6-May-2017 6:47:58 PM
There are few different Stackoverflow tickets for the same error message, but they're for different scenarios. In mine here it looks like a method who takes an Int parameter is being rejected. If you could please give me a hint this would help me a lot.

Rename the guess parameter (or the method name, so it's something different) - the parameter is the first guess in scope, so the compiler thinks you're trying to call it as a function.

Related

Akka group runForeach

I have an akka source that I want to group and run on batch. I am facing a problem and I am not really sure what is going wrong.
I have a source that looks something like this
val source = Source(facts.toList)
source
.grouped(config.batchSize)
.runForeach(batch => {
//Do something
})
But I am getting
[error] found : scala.concurrent.Future[akka.Done]
[error] required: scala.concurrent.Future[Unit]
[error] .runForeach(batch => {
[error]
^
Why isn't it not able to run the source?
You're not showing the larger context in which your code snippet resides, but I'm guessing your code is the last expression inside a method that is expecting a return value of Future[Unit]. The compiler is complaining because Source#runForeach returns a Future[Done] instead of a Future[Unit].
A quick fix could be to change your method's return type to Future[Done].

Scala test unexpected error,')' expected but '}' found

Here is my code to find maximum from list
object kp {
def main(args: Array[String]) {
def max(xs: List[Int]): Int = xs match {
case Nil => throw new java.util.NoSuchElementException()
case List(x: Int) => x
case x :: y :: rest => max( (if (x > y) x else y) :: rest )
}
val a = 1 :: 4 :: 5 :: -4:: Nil
println(max(a))
}
}
When I want to test my codes in example folder with sbt
[info] Compiling 1 Scala source to /home/milenko/example/target/scala-2.11/classes...
[error] /home/milenko/example/src/main/scala/example/ListsSuite.scala:138: ')' expected but '}' found.
[error] }
[error] ^
[error] /home/milenko/example/src/main/scala/example/ListsSuite.scala:148: ')' expected but '}' found.
[error] }
[error] ^
[error] two errors found
Errors refer to
test("maximum with one negative number") {
assert(max(List(1,4,5,-4)) === 5 )
}
and
test("maximum with some repeated elements"){
assert(max(List(2,2,2,2)) === 2 )
}
I do not have a clue why this happens.Here is the whole file
http://www.filedropper.com/listssuite
Now I have deleted some test from the file and it has only 135 lines.But I got the same
wc -l ListsSuite.scala
135 ListsSuite.scala
milenko#milenko-desktop:~/example/src/test/scala/example$ cd ~/example
milenko#milenko-desktop:~/example$ sbt
[info] Loading global plugins from /home/milenko/.sbt/0.13/plugins
[info] Loading project definition from /home/milenko/example/project
[info] Set current project to progfun1-example (in build file:/home/milenko/example/)
> test
[info] Compiling 1 Scala source to /home/milenko/example/target/scala-2.11/classes...
[error] /home/milenko/example/src/main/scala/example/ListsSuite.scala:138: ')' expected but '}' found.
[error] }
[error] ^
[error] /home/milenko/example/src/main/scala/example/ListsSuite.scala:148: ')' expected but '}' found.
[error] }
[error] ^
[error] two errors found
[error] (compile:compileIncremental) Compilation failed
[error] Total time: 1 s, completed 16/03/2017 13:43:43
Very strange, what do :138 and :148 indicate?
I can't see anything in the filedropper link (maybe it's expired?), but I know that one error that causes a similar compiler error is a trailing comma. I don't think this is your problem, but understanding what the compiler is doing could be helpful in your case.
Here it is in a simple file Comma.scala:
val map = Map(
1 -> "one",
2 -> "two", // <--- comma after last argument
)
Trying to compile this with scala 2.11 gives:
$ scala Comma.scala
Comma.scala:4: error: illegal start of simple expression
)
^
Comma.scala:4: error: ')' expected but eof found.
)
^
two errors found
The second error is like your one.
My guess is that:
the "illegal start of simple expression" is because it's expecting an expression after the last comma (e.g. 3 -> "three") but it's encountering the closing bracket instead which it deems to not be a valid expression
because the closing bracket got consumed earlier whilst parsing the arguments to Map(..), when the compiler finishes processing the arguments it goes up one level to find the closing ')' for the Map(, but hits something else (in my case, end of file and in your case a '}' from an enclosing block of code. This yields the error ')' expected but ... found
That second error matches your one so it could point to something going wrong where it's parsing your arguments and eating your closing bracket. The message itself is a red herring as it points to the closing bracket when the real problem could be earlier.
If you're a python developer who is used to trailing brackets this can lead to a lot of head scratching!
I had one case where the scala 2.12 compiler could actually handle the trailing comma, but unfortunately I can't reproduce it with a small example suitable for SO. This slight difference can unfortunately create non-backwards compatible code between 2.12 and previous versions.

java generics in scala sometimes fail with cast exception

So this is a pretty specific problem, but might be related to issues other may have experience, though I could not find a good solution.
in our specific case, we are using Elasticsearch. the problematic piece of code is this:
val hit: org.elasticsearch.search.SearchHit = {...}
val innerSystemField: Option[Long] =
Try(hit.field("system.innerField").getValue) match {
case Success(x) => Some(x.asInstanceOf[Long])
case Failure(e) => {
logger.error("exception during innerField retrieval", e)
None
}
}
so, it doesn't really matters we are using Elasticsearch, what matter, is the library API. so, here's the SearchHit interface's field method which returns an instance of SearchHitField. and here's the SearchHitField interface's getValue method. the method is declared as:
<V> V getValue();
and this is where the problem lies. the mapping which we defined Elasticsearch with, guarantee that the returned value will always be a Long. but every once in a while we get a Failure containing a java.lang.ClassCastException: java.lang.Long cannot be cast to scala.runtime.Nothing$. The thing is, that if I explicitly write the type, it won't compile:
[error] /home/me/projects/my-project/src/main/scala/com/org/project/MyElasticsearchCode.scala:123: polymorphic expression cannot be instantiated to expected type;
[error] found : [V]()V
[error] required: Long
[error] Try[Long](hit.field("system.innerField").getValue) match {
[error] ^
[error] one error found
[error] (project/compile:compileIncremental) Compilation failed
[error] Total time: 4 s, completed Jul 27, 2015 4:16:41 PM
So how do I get around this problem?
I find the message of the ClassCastException a bit confusing. Maybe you could try this:
val innerSystemField: Option[Long] =
Try[Any](hit.field("system.innerField").getValue) match {
case Success(x: java.lang.Long) => Some(x.asInstanceOf[Long])
case Failure(e) => {
logger.error("exception during innerField retrieval", e)
None
}
}

Type mismatch error upon compiling project with ScalaFX in SBT

I'm developing a project with ScalaFX and MySQL database.
SBT successfully added MySQL connector via build.sbt file. When it compiles the project, it stops with a type mismatch error:
[error] found : com.aitrich.scalafx.test.DbConnection.type (with underlying type object com.aitrich.scalafx.test.DbConnection)
[error] required: com.aitrich.scalafx.test.DbConnection
[error] val orders: Seq[Person] = OrderDao.getAllOrders(dbc)
[error] ^
[error] one error found
[error] (compile:compile) Compilation failed
[error] Total time: 14 s, completed Nov 14, 2013 12:04:06 PM
The following is a code snippet from the main method:
var dbc = DbConnection
val orders: Seq[Person] = OrderDao.getAllOrders(dbc)
This is the DbConnection case class:
case class DbConnection() {
def getConnectionString =
"jdbc:mysql://%s:3306/simpleorder?user=%root&password=%sa".
format("localhost","root","sa")
}
Why does compile fail?
tl;dr You need to instantiate (create an instance of) DbConnection case class.
It's in no way SBT's or ScalaFX's issue.
What you pass as an argument to OrderDao.getAllOrders method is a type not an instance of a type. The types simply don't match and the Scala compiler breaks compilation (that's exactly the reason to use Scala in the first place - a thorough type checking at compile time).
Change the line
var dbc = DbConnection
to
var dbc = new DbConnection
and the compiler gets pass that line. Note the new keyword.

Gatling gives error when using parameter for ramp

I'm using a parameter for my ramp value as per the docs,
val rampUpRate = Integer.getInteger("ramp", 1)
setUp(
scn.users(10).ramp(rampUpRate).protocolConfig(httpConf)
)
But when I run gatling, I'm getting an error:
09:57:35.695 [ERROR] c.e.e.g.a.ZincCompiler$ - /Gatling/user-files/simulations/clients/com/mydomain/www/stress/RecordedSimulation.scala:1088: overloaded method value ramp with alternatives:
(duration: akka.util.Duration)com.excilys.ebi.gatling.core.scenario.configuration.ConfiguredScenarioBuilder <and>
(duration: Long)com.excilys.ebi.gatling.core.scenario.configuration.Configured
ScenarioBuilder
cannot be applied to (java.lang.Integer)
I thought I could simply cast to Long before using the parameter
val rampUpRate = Integer.getInteger("ramp", 1)
setUp(
scn.users(10).ramp((Long) rampUpRate).protocolConfig(httpConf)
)
but this still errors:
09:57:35.695 [ERROR] c.e.e.g.a.ZincCompiler$ - /Gatling/user-files/simulations/clients/com/mydomain/www/stress/RecordedSimulation.scala:1088: \sanctuarySpa\com\sanctuaryspa\www\stress\RecordedSimulation.scala:1088:
value rampUpRate is not a member of object Long
10:05:34.915 [ERROR] c.e.e.g.a.ZincCompiler$ - scn1.users(10).ramp((Long) rampUpRate).protocolConfig(httpConf),
Any suggestions why following the documentation, or the explicit cast to long don't work?
Try using rampUpRate.toLong to cast to a Long (or the more general cast rampUpRate.asInstanceOf[Long])
(Long) rampUpRate is seen by the compiler as trying to perform Long.rampUrRate() e.g. applying function rampUpRate to object Long, hence the error message
That's my fault: the wiki page is not up to date.
What happens is that you have a java.lang.Integer while the method takes a scala Long. java.lang.Long can be implicitly converted into scala Long, but not java.lang.Integer.
The proper way would be val rampUpRate = java.lang.Long.getLong("ramp", 1L)
PS: I've fixed the doc.