1

I've defined a class that has a method in it that is trying to make use of a function with an implicit parameter in it. Unfortunately it's failing to compile

class Test {
    def useImplicit(implicit a: Boolean) = a
    def getAnswer() = if (useImplicit) println("yes") else println("no") 
}

object Preferences {
    implicit val yes = false
    implicit val no = false
}

The problem is that when I go to compile the class to try and test it out I get the error

could not find implicit value for parameter a: Boolean
   def getAnswer() = if (useImplicit) println("yes") else println("no")

I'm not exactly sure what is going on here. The reason for me trying it this way is I am ultimately wanting to overload hashCode and determine at runtime whether I should run my overloaded version or call the parent implementation. If this isn't possible I suppose I could make the class take an implicit

1 Answer 1

1

getAnswer is calling useImplicit, but there is no implicit Boolean within the scope of Test. getAnswer will also require the implicit parameter to work:

def getAnswer(implicit a: Boolean) = if(useImplicit) println("yes") else println("no")

The alternative is making Test require the implicit on instantiation, as you say.

Sign up to request clarification or add additional context in comments.

1 Comment

The ultimate problem is I'm trying to override a function at runtime. I can't add the parameter to the getAnswer method due to the fact that it would change the method signature and therefor not be executed by the calling code. I just realized I need to use a trait and mix it in at run time when creating the object.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.