简体   繁体   English

Scala隐式类参数

[英]Scala implicit class parameter

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? 为什么Scala实例化隐式方法要求您在此实例中使用空白参数调用对象? Why is there an implicit blank parameter list presented for such object instances? 为什么为此类对象实例提供了隐式空白参数列表?

First, Test is not an implicit class. 首先, Test 不是隐式类。 See this for a discussion of implicit classes. 这个隐类的讨论。

Instead, Test is a class that has no explicit constructor arguments but one implicit String argument. 相反, Test是一个没有显式构造函数自变量但只有一个implicit String变量的类。 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." 这意味着您可以实例化Test的唯一方法是像您一样显式地提供隐式参数,这很尴尬并且无法实现目的,或者在实例化时在implicit作用域中提供一个且仅一个String并让编译器“选择它”。 “起来。

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: 然后,您需要实例化Test是:

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. 但是,最主要的是确保您隐式参数和隐式类之间有所区别。

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. 我认为这可能是因为解析器需要区分对类型Test(或同伴对象)的引用与对构造函数的引用。 If it allowed a constructor with no arguments, then Test by itself would be ambiguous. 如果它允许没有参数的构造函数,那么Test本身将是模棱两可的。

Normally in scala when you refer to an "implicit class" you do it like this: 通常在scala中,当您引用“隐式类”时,您会像这样进行操作:

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

Then you can do: 然后,您可以执行以下操作:

import Container._

and it will implicitly convert Strings into Test objects. 它将隐式地将字符串转换为Test对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM