2

I have a class with an implicit parameter defined as:

 class Test(implicit one: String)

And I want to instantiate that object like so:

val grr = new Test("aha")

I get the following exception.

error: too many arguments for constructor Test: ()(implicit one: String)Test
       val grr = new Test("aha")

But if I call it like so

val grr = new Test()("haha")
grr: Test = Test@3bd40a57

I get a Test object.

Why does Scala instantiate of implicit methods require you to call the object with blank parameters in this instance? Why is there an implicit blank parameter list presented for such object instances?

2 Answers 2

5

First, Test is not an implicit class. See this for a discussion of implicit classes.

Instead, Test is a class that has no explicit constructor arguments but one implicit String argument. This means the only way you can instantiate Test is to either provide the implicit argument explicitly as you did, which is awkward and defeats the purpose, or to provide one and only one String in implicit scope at instantiation time and have the compiler "pick it up."

In other words, if you have something like this in scope:

implicit val s: String = "haha"

Then all you will have to do to instantiate Test is this:

val grr = new Test

And if you don't have one in scope, the compiler will let you know it. That's a good thing.

The main thing though is to make sure you get the distinction between implicit parameters and implicit classes.

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

Comments

0

The implicit blank parameter list is there just for constructors, not all methods. I think this is probably because the parser needs to distinguish between a reference to the type Test (or the companion object) and a reference to the constructor. If it allowed a constructor with no arguments, then Test by itself would be ambiguous.

Normally in scala when you refer to an "implicit class" you do it like this:

object Container {
   implicit class Test(val one: string)
}

Then you can do:

import Container._

and it will implicitly convert Strings into Test objects.

1 Comment

right, but i'm looking to encapsulate an implicit parameter within a class to give that to the class within certain scopes rather than implicitly convert strings to test classes. i guess my example was a little contrived. i guess i'm a little confused by you saying that test would be ambiguous with no constructor - is that ambiguous from the object Test that gets created with the class then?

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.