Scala中的类型参数的默认值 [英] Default value for type parameter in Scala

查看:411
本文介绍了Scala中的类型参数的默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法弄清楚(如果有的话)可以为Scala中的 type 参数设置默认值。

目前我有一个类似的方法对此:

  def getStage [T<:Stage](key:String):T = {
/ /做花哨的东西,返回一些东西
}

但是我想要做的是提供 getStage 的实现,它不会为<$​​ c $ c> T 赋值,而是使用默认值。我试图只定义另一种方法并重载参数,但它只会导致其中一种方法被另一种方法完全覆盖。如果我不清楚我想要做的是这样的:

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

}



<我希望这很清楚我要求什么。有人知道这样的事情可以实现吗?

解决方案

您可以使用类型安全的方式来做这种事情类型的类。例如,假设你有这样的类:

  trait默认[A] {def apply():A} 

以下类型层次结构:

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

以及一些实例:

  trait LowPriorityStageInstances {
隐式对象barStageDefault extends缺省值[BarStage] {
def apply()= BarStage(13)
}
}

对象Stage extends LowPriorityStageInstances {
隐式对象stageDefault extends Default [Stage] {
def apply()= FooStage(foo)
}
}

$ b然后你可以这样编写你的方法:

$ $ $ $ $ $ c $ def $ getStage [ T<:Stage:Default](key:String):T =
隐含[Default [T]]。apply()

它的工作原理是这样的:

 阶> getStage()
res0:Stage = FooStage(foo)

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

其中我想或多或少是你想要的。


I'm failing to figure out how (if at all) you can set a default value for a type-parameter in Scala.
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. 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.

这篇关于Scala中的类型参数的默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆