0

The method have a implicit parameter can not be reference as argument ? In my code ,i create a method that have a implicit parameter. Some time i just want to transfer it to other method . In this time Scala give me error. See below:

case class ComplicatedSalesTaxData(baseRate: Float,isTaxHoliday: Boolean) 
def calcText(amount: Float,rate : (ComplicatedSalesTaxData) => Float ) : Float = amount * rate(ComplicatedSalesTaxData(0.06F,false))
def rate(implicit cstd:ComplicatedSalesTaxData) = {
if(cstd.isTaxHoliday) 
    cstd.baseRate
else 
    0.01F }

calcText(100F,rate) // will get error : could not find implicit value for parameter cstd: ComplicatedSalesTaxData
2
  • where is the implicit instance of ComplicatedSalesTaxData ? Commented May 12, 2017 at 7:52
  • Any place i will declare it, but not here . In here i just want to transfer the 'rate' method to 'calcText' and invoke with a specify 'ComplicatedSalesTaxData' that create in 'calcText' Commented May 12, 2017 at 8:37

2 Answers 2

2

You have to say that you want to pass the parameter explicitly:

calcText(100F,rate(_)) 
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks ,but in this case "rate(_)" is a anonymous method and not a reference .
It's actually an anonymous function. If you had defined rate with explicit parameter, passing rate as parameter to calcText would not pass a reference to the method rate (a method is not an object, it does not have references), but to the Function1 object defined by this method. So it all comes down to the same thing, basically. The difference here is that when given no parameters, rate is assumed to be applied to the implicit in scope, rather than considered as a function.
0

The error message that you have posted says that the compiler cannot find an implicit ComplicatedSalesTaxData in the current scope. Therefore you have to define one. Then the call should look like this calcText(100F,rate(_)) instead of the wildcard _ you can also pass the value explictely.

Comments

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.