scala

时间:2015-12-14 15:02:35

标签: scala generics

我试图找出一种摆脱重载方法的方法。目前我使用这种方法为用户提供了很好的API:

  def get(id: String): Option[JsonDocument]

  def get(id: String, timeout: Duration): Option[JsonDocument]

  def get[D <: Document[_]](id: String, target: Class[D]): Option[D]

  def get[D <: Document[_]](id: String, target: Class[D], timeout: Duration): Option[D]

既然scala有默认参数,我想把它压缩成一个方法。但由于D是通用的,我需要默认值,如果没有提供不是&#34;没有&#34;,而是&#34; JsonDocument&#34;。

我目前的方法是这样做的:

  def get[D <: Document[_]](id: String, target: Class[D] = classOf[JsonDocument], timeout: Duration = null): Option[D]

事实证明编译器对此非常满意,但IDE存在问题。如果未明确提供目标(如使用target = JsonDocument或任何其他目标),则认为返回类型为Option [Nothing],因此会使用户感到困惑。

所以我的问题是:对于这些类型,是否可以提供&#34;默认&#34;类型D的JsonDocument的类型,如果用户没有提供它来覆盖?

1 个答案:

答案 0 :(得分:2)

http://www.cakesolutions.net/teamblogs/default-type-parameters-with-implicits-in-scala给出了默认通用参数问题的解决方案。适用于您的情况,您会得到类似(未经测试)的内容:

trait DefaultsTo[Type, Default]

object DefaultsTo {
  implicit def defaultDefaultsTo[T]: DefaultsTo[T, T] = null
  implicit def fallback[T, D]: DefaultsTo[T, D] = null  
}

// use target.runtimeClass in the implementation
def get[D <: Document[_]](id: String, timeout: Duration)(implicit target: scala.reflect.ClassTag[D], default: DefaultsTo[D, JsonDocument]): Option[D]

get(id, timeout)JsonDocument使用get[OtherDocument](id, timeout)。当然,IDE(IntelliJ?)是否能够正确地推断出类型是一个不同的问题!