Default value for type parameter in Scala

前端 未结 1 558
青春惊慌失措
青春惊慌失措 2021-02-02 13:31

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         


        
相关标签:
1条回答
  • 2021-02-02 14:02

    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.

    0 讨论(0)
提交回复
热议问题