could not find implicit value for param in scala - scala

Stuck with a compilation error in my scala code
that reads implicit value could not be found . Could somebody point out what I am doing wrong?
Error :
could not find implicit value for evidence parameter of type scopt.Read[Array[String]]
opt[Array[String]](
^
one error found
My code
case class Myclass (
listC: Array[String] = Array()
)
object Myclass {
def parseArgs(args: Seq[String]): Myclass = {
val parser = new scopt.OptionParser[Myclass](
"ValidateData") {
opt[Array[String]](
"disabled.implicit.assertions") optional () action { (x, c) =>
c.copy(disabledImplicitAssertions = x)
}
}
}

Related

Testing private methods that take generic type using PrivateMethodTester

How can I test a private method that takes a generic type using privateMethodTester in scala?
Let's say I have the following method:
private def parseValueForJsonKeyWithReturnType[A: TypeTag](
node: JsonNode,
key: String,
defaultValue: Option[A] = None): A = {
val parsedValue = Option(node.get(key)).map(value => {
typeOf[A] match {
case t if t =:= typeOf[String] =>
value.textValue()
case t if t =:= typeOf[Double] =>
value.asDouble()
case t if t =:= typeOf[Long] =>
value.asLong()
case _ => throw new RuntimeException(s"Doesn't support conversion to [type=${typeOf[A]}] for [key=${key}]")
}
})
parsedValue.getOrElse(defaultValue.get).asInstanceOf[A]
}
I can call the method like this
parseValueForJsonKeyWithReturnType[Boolean](jsonNode, key="hours")
parseValueForJsonKeyWithReturnType[String](jsonNode, key="hours")
parseValueForJsonKeyWithReturnType[Long](jsonNode, key="hours")
In the test, I'm trying to do
val parseValueForJsonKeyWithReturnTypeInt = PrivateMethod[Int]('parseValueForJsonKeyWithReturnType)
a[RuntimeException] shouldBe thrownBy (object invokePrivate parseValueForJsonKeyWithReturnType[Int](jsonNode, "total" , None))
to make sure it will throw Runtime exception for unsupported type
But I get this error:
error: value parseValueForJsonKeyWithReturnType of type SerializerTest.this.PrivateMethod[Int] does not take type parameters.
If i try without type parameters, build succeeds but i get illegalArgumentException
Expected exception java.lang.RuntimeException to be thrown, but java.lang.IllegalArgumentException was thrown.
Cause: java.lang.IllegalArgumentException: Can't find a private method named: parseValueForJsonKeyWithReturnType
What am I doing wrong? Probably the syntax is wrong.
I got the same issue with "Can't find a private method named" on Scala 2.13 and ScalaTest 3.2.14. So i walked into the Scastie to make an example for GitHub issue. But there it actually worked!
The only thing i have in my code which i didn't add to this test was object extending class like this:
class WithPrivate
object WithPrivate extends WithPrivate
When i test just with object SomePrivateMethods with private methods - ScalaTest finds the private methods in all possible ways:
import org.scalatest.{PrivateMethodTester}
import org.scalatest.wordspec.AnyWordSpec
import org.scalatest.matchers.must.Matchers
// this will fail if you uncomment it with object extends lower in code
//class WithPrivate {
object WithPrivate {
private def toString (i: Int): String = i.toString ()
private def sumToString (i1: Int) (i2: Int): String = (i1 + i2).toString ()
private def somethingToString [T] (t: T): String = t.toString ()
private def somethingToSomething [I, O] (i: Seq [I]) (f: I => O): Seq [O] =
i.map (f)
}
// uncomment this if you uncomment class WithPrivate
//object WithPrivate extends WithPrivate
class Test extends AnyWordSpec with Matchers with PrivateMethodTester {
"test" must {
"work with simple method" in {
val method =
PrivateMethod [String] (Symbol ("toString"))
WithPrivate.invokePrivate (method (1)) mustBe "1"
}
"fail with name error on simple method with wrong arguments" in {
val method =
PrivateMethod [String] (Symbol ("toString"))
// Can't find a private method named: toString
WithPrivate.invokePrivate (method (1, 2)) mustBe "1"
}
"work with multiple arguments list" in {
val method =
PrivateMethod [String] (Symbol ("sumToString"))
WithPrivate.invokePrivate (method (1, 2)) mustBe "3"
}
"work with generics" in {
val method =
PrivateMethod [String] (Symbol ("somethingToString"))
WithPrivate.invokePrivate (method (1)) mustBe "1"
}
"work with high-order functions" in {
val method =
PrivateMethod [Seq [String]] (Symbol ("somethingToSomething"))
def f: Int => String = _.toString
WithPrivate.invokePrivate (method (Seq (1, 2), f)) mustBe List ("1", "2")
}
}
}
new Test ().execute ()
https://scastie.scala-lang.org/0eQtkQNzTNm5BNhDEIlIng
So if you are having such issue - check if you are testing object or class.

Scala ADT Type Mismatch

I'm puzzled by the compile error for the line that defines endState. Here is the code:
import java.util.UUID
object Evaluation {
def default: Evaluation[Unit, Unit] = new Evaluation[Unit, Unit](identity)
}
case class Evaluation[From, +To](evaluate: (From) => To)
object FSMLike {
val uuidEmpty: UUID = new UUID(0L, 0L)
val endState: Evaluation[Unit, FSMLike[Nothing]] = new Evaluation(() => FSMEmpty)
lazy val stop: FSMEntry[Unit, Unit, Nothing] = FSMEntry(uuidEmpty, Evaluation.default, endState)
def apply[From1, From2, To](
action: Evaluation[From1, Unit],
nextState: Evaluation[From2, FSMLike[To]]
): (UUID, FSMLike[To]) = {
val uuid = UUID.randomUUID
uuid -> FSMEntry(uuid, action, nextState)
}
}
sealed trait FSMLike[+A]
case object FSMEmpty extends FSMLike[Nothing]
case class FSMEntry[From1, From2, +To](
id: UUID,
action: Evaluation[From1, Unit],
nextState: Evaluation[From2, FSMLike[To]]
) extends FSMLike[To] {
def transition(arg1: From1, arg2: From2): FSMLike[To] = {
action.evaluate(arg1)
nextState.evaluate(arg2)
}
override def toString: String = s"^$id^"
}
Here is the error:
Error:(14, 72) type mismatch;
found : () => FSMEmpty.type (with underlying type () => FSMEmpty.type)
required: Unit => FSMLike[Nothing]
val endState: Evaluation[Unit, FSMLike[Nothing]] = new Evaluation(() => FSMEmpty)
You are trying to pass () => FSMEmpty, a function with no arguments, where a function with one argument of type Unit is expected. Sure, when you use () as an expression, it's the only value of type Unit, but the left-hand side of => isn't an expression.
You should write _ => FSMEmpty instead. { case () => FSMEmpty } would work as well, I think, but there isn't much point to using it.

In Scala, how to use reflection to get the real type of varargs parameters for method

I'm using reflection to get parameter type of method, but there is some problem with varargs. Here is my code:
import reflect.runtime.universe._
case class C() {
def f(x: String*) = x
}
object Main {
def main(args: Array[String]): Unit = {
val c = C()
val r = runtimeMirror(getClass.getClassLoader).reflect(c)
val x = r.symbol.typeSignature.member(newTermName("f"))
val params = x.asMethod.paramss.head.map {
_.typeSignature.typeSymbol
}
for (param <- params) {
println(param)
}
}
}
The result is:
> class <repeated>
How can I get the real type String? Or is there any way else to do this?
Use _.typeSignature.typeArgs.head, because String is a type argument of String*, not its typeSymbol.
Your parameter x is type of String*. That is what you get by calling:
_.typeSignature.typeSymbol
but String* is intrepreted as Seq[String] (as we all know). Thus calling:
_.typeSignature.typeArgs
will get you your type arguments, i.e. your desired String.
Btw. if you want to prove that String* is Seq just call:
_.typeSignature.erasure
So your modified code should look like (omitting class C):
val c = C()
val r = runtimeMirror(getClass.getClassLoader).reflect(c)
val x = r.symbol.typeSignature.member(newTermName("f"))
val params = x.asMethod.paramss.head.map {
_.typeSignature.typeArgs
}
for (param <- params) {
println(param)
}
it will print List(String).
Enjoy

Scala: 'missing parameter type' when calling scala macro with a PartialFunction reify

The compiler is throwing me a 'Missing parameter type'. After cornering the problem I've realized that when chaining Partial Functions you need to be explicit about the types or the compiler will throw the mentioned error. Now, do you guys know if there are any issues when chaining partial functions inside a macro's reify? I think I couldn't be more explicit about the partial function types:
object Implementations{
def missingParamType_impl(c: whitebox.Context)(a: c.Expr[Int]):c.Expr[PartialFunction[Int,String]] = {
import c.universe._
reify {
val spliced = a.splice
val spliced2 = a.splice * 2
((PartialFunction.apply[Int,String]{
case `spliced` ⇒ a.splice.toString
} : PartialFunction[Int,String]).orElse[Int,String]{
case `spliced2` ⇒ a.splice.toString
} : PartialFunction[Int,String]) : PartialFunction[Int,String]
}
}
}
This is how I call the macro implementation:
object Macros {
def missingParamType(a: Int):PartialFunction[Int,String] = macro Implementations.missingParamType_impl
}
I have also tried this:
def missingParamType_impl(c: whitebox.Context)(a: c.Expr[Int]):c.Expr[PartialFunction[Int,String]] = {
import c.universe._
reify {
val spliced = a.splice
val spliced2 = a.splice * 2
val pf1: PartialFunction[Int, String] = {
case `spliced` ⇒ a.splice.toString
}
val pf2: PartialFunction[Int, String] = {
case `spliced2` ⇒ a.splice.toString
}
val PF:PartialFunction[Int, String] = pf1.orElse(pf2)
PF
}
}
Or am I fundamentally misunderstanding how reify works?
Unfortunately, this looks like a known issue: https://issues.scala-lang.org/browse/SI-6619.

Specs2 and #Before/#After-like methods

Given the code like:
class RESTAcceptanceTest extends Specification {
override def is = anonymous ^ signinOAuth
def anonymous = "Something" ^ givenSomething ^
"must happen" ^ mustHappen
end
def signinOAuth = "Signin" ^ givenSignin ^
"works as expected" ^ userExistsInDatabase
end
// rest of object definitions
}
how do I ensure that same before and after code is executed before/
after "anonymous" and "signinOAuth", and the "after" method should
execute even if test is failing itself?
If you're using Given/When/Then steps you can use a Context to control what gets executed before and after each example:
import org.specs2._
import specification._
class MySpec extends Specification { def is =
"anonymous" ^
"something" ^ something ^
"must happen" ^ mustHappen ^ endp^
"OAuth"^
"signing" ^ signing ^
"works ok" ^ worksOk
lazy val something: Given[Int] = (s: String) => { s.pp; 1 }
lazy val mustHappen: Then[Int] = (i: Int) => (s: String) =>
context { s.pp; i must_== 1 }
lazy val signing: Given[Int] = (s: String) => { s.pp; 2 }
lazy val worksOk: Then[Int] = (i: Int) => (s: String) =>
context { s.pp; i must_== 2 }
lazy val context = new BeforeAfter {
def before = "before".pp
def after = "after".pp
}
}
In the code above the apply method of the context object is used to wrap the code to execute with before and after. Also if you add an error to one of the examples you will see that the "after" code is always executed.
PS: pp is a utility method like println to display something in the terminal during the execution. The advantage over println is that it returns its argument so you can write 1.pp must_== 1
Have a look at the documentation: http://etorreborre.github.com/specs2/guide/org.specs2.guide.Structure.html#Before/After