Scala中方法的默认泛型类型 [英] Default generic type on method in scala
问题描述
我正在尝试找出一种方法来摆脱重载方法.目前,我正在使用这种方法向用户提供不错的API:
I'm trying to figure out a way to get away from overloaded methods. Currently I'm using this approach to provide nice APIs to the user:
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是通用的,所以如果没有提供,我需要使用默认值,而不是"Nothing",而是"JsonDocument".
Now since scala has default parameters I want to condense this into one method. But because D is generic, I need the default if not provided not to be "Nothing", but rather "JsonDocument".
我目前的做法是:
def get[D <: Document[_]](id: String, target: Class[D] = classOf[JsonDocument], timeout: Duration = null): Option[D]
事实证明,编译器对此感到非常满意,但是IDE存在问题.如果未显式提供目标(例如target = JsonDocument或任何其他目标),则它认为返回类型为Option [Nothing],因此会使用户感到困惑.
And as it turns out the compiler is super happy with it, but the IDE has problems. if the target is not explicitly provided (like with target = JsonDocument or any other) it thinks the return type is Option[Nothing] and therefore its confusing to the user.
所以我的问题是:对于这些类型,如果用户未提供要覆盖的D类型的JsonDocument,是否可以提供默认"类型的JsonDocument?
So my question is: with these types, is it possible to provide a "default" type of JsonDocument for type D if it is not provided by the user to be overridden?
推荐答案
There is an solution to the default generic parameters problem given at http://www.cakesolutions.net/teamblogs/default-type-parameters-with-implicits-in-scala. Applying to your case, you'd get something like (untested):
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]
要使用: JsonDocument
的 get(id,timeout)
或 get [OtherDocument](id,timeout)
的 get(id,timeout)
.当然,IDE(IntelliJ?)是否能够正确推断类型是另一个问题!
To use: get(id, timeout)
for JsonDocument
or get[OtherDocument](id, timeout)
. Of course, whether the IDE (IntelliJ?) is going to infer the type correctly is a different question!
这篇关于Scala中方法的默认泛型类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!