2
votes

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

2 Answers

5
votes

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.

0
votes

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.