Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/scala/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
scala:具有类型标记的类的空构造函数_Scala - Fatal编程技术网

scala:具有类型标记的类的空构造函数

scala:具有类型标记的类的空构造函数,scala,Scala,考虑以下类的定义 case class DiscreteProperty[T <: AnyRef]( name: String, sensor: T => String, range: Option[List[String]] )(implicit val tag: ClassTag[T]) extends TypedProperty[T, String] { /// some stuff here } 我想这是因为类没有空构造函数。如何为此类定义空构造函数?我

考虑以下类的定义

case class DiscreteProperty[T <: AnyRef](
  name: String,
  sensor: T => String,
  range: Option[List[String]]
)(implicit val tag: ClassTag[T]) extends TypedProperty[T, String] {

  /// some stuff here 
}
我想这是因为类没有空构造函数。如何为此类定义空构造函数?我尝试了以下操作,但出现以下错误:

  def this() {
    this("funnyName", T => "" ,Option(List()))
  }
这些都不管用:

  def this[T]() {
    this("funnyName", T => "" ,Option(List()))
  }


你知道如何用type标记为这个类创建一个空构造函数吗

问题是您没有在任何空构造函数中包含隐式参数。您将主构造函数视为具有签名
(String,T=>String,Option[List[String]])
,但这并不完全正确。实际上,它是
(String,T=>String,Option[List[String]])(ClassTag[T])
(注意
ClassTag
参数)

通常这不会成为问题,因为隐式参数将从该构造函数的作用域中检索。然而,类标记有点特殊——它在编译时用与
T
相对应的类标记填充。每个辅助构造函数的问题是
T
仍然是泛型的,因此编译器不知道要包含哪个类标记:在该范围内没有可用的隐式参数

那么,你怎么能修复它呢?最简单的方法可能是在任何辅助构造函数中包含隐式参数:

def this()(implicit tag: ClassTag[T]) = this("funnyName", T => "", Option(List()))
注意,您不需要向链式构造函数显式地证明
ClassTag
;它现在是作用域的一部分,将被隐式使用。当然,您可以这样明确地决定:

def this()(implicit tag: ClassTag[T]) = this("funnyName", T => "", Option(List()))(tag)

问题是您没有在任何空构造函数中包含隐式参数。您将主构造函数视为具有签名
(String,T=>String,Option[List[String]])
,但这并不完全正确。实际上,它是
(String,T=>String,Option[List[String]])(ClassTag[T])
(注意
ClassTag
参数)

通常这不会成为问题,因为隐式参数将从该构造函数的作用域中检索。然而,类标记有点特殊——它在编译时用与
T
相对应的类标记填充。每个辅助构造函数的问题是
T
仍然是泛型的,因此编译器不知道要包含哪个类标记:在该范围内没有可用的隐式参数

那么,你怎么能修复它呢?最简单的方法可能是在任何辅助构造函数中包含隐式参数:

def this()(implicit tag: ClassTag[T]) = this("funnyName", T => "", Option(List()))
注意,您不需要向链式构造函数显式地证明
ClassTag
;它现在是作用域的一部分,将被隐式使用。当然,您可以这样明确地决定:

def this()(implicit tag: ClassTag[T]) = this("funnyName", T => "", Option(List()))(tag)