简体   繁体   English

Scala中类型参数的默认值

[英]Default value for type parameter in Scala

I'm failing to figure out how (if at all) you can set a default value for a type -parameter in Scala. 我没有弄清楚如何(如果有的话)你可以在Scala中为type -parameter设置默认值。
Currently I have a method similar to this: 目前我有一个类似于此的方法:

def getStage[T <: Stage](key: String): T = {
  // Do fancy stuff that returns something
}

But what I'd like to do is provide an implementation of getStage that takes no value for T and uses a default value instead. 但我想要做的是提供一个getStage的实现,它不会为T取任何值,而是使用默认值。 I tried to just define another method and overload the parameters, but it only leads to one of the methods being completely overriden by the other one. 我试图定义另一个方法并重载参数,但它只导致其中一个方法被另一个方法完全覆盖。 If I have not been clear what I'm trying to do is something like this: 如果我不清楚我想要做的是这样的事情:

def getStage[T<:Stage = Stage[_]](key: String): T = {

}

I hope it's clear what I'm asking for. 我希望很清楚我要求的是什么。 Does anyone know how something like this could be achieved? 有谁知道这样的事情是如何实现的?

You can do this kind of thing in a type-safe way using type classes. 您可以使用类型类以类型安全的方式执行此类操作。 For example, suppose you've got this type class: 例如,假设您有这个类型类:

trait Default[A] { def apply(): A }

And the following type hierarchy: 以下类型层次结构:

trait Stage
case class FooStage(foo: String) extends Stage
case class BarStage(bar: Int) extends Stage

And some instances: 还有一些例子:

trait LowPriorityStageInstances {
  implicit object barStageDefault extends Default[BarStage] {
    def apply() = BarStage(13)
  }
}

object Stage extends LowPriorityStageInstances {
  implicit object stageDefault extends Default[Stage] {
    def apply() = FooStage("foo")
  }
}

Then you can write your method like this: 然后你可以像这样编写你的方法:

def getStage[T <: Stage: Default](key: String): T =
  implicitly[Default[T]].apply()

And it works like this: 它的工作原理如下:

scala> getStage("")
res0: Stage = FooStage(foo)

scala> getStage[BarStage]("")
res1: BarStage = BarStage(13)

Which I think is more or less what you want. 我认为或多或少是你想要的。

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

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