Scala type keyword: how best to use it across multiple classes

前端 未结 3 1292
无人及你
无人及你 2021-02-01 11:36

Coming back to Scala after a spell writing Haskell, I\'ve started using the type keyword to make my class definitions a bit more readable, eg:

type RestfulParams         


        
相关标签:
3条回答
  • 2021-02-01 12:20

    Youn can use a package object and put the type declaration in there. When you import that package the type definition will be available.

    An example :

    //package myType
    package object myType {type mine = List[String]}
    

    Notice that the package object has the same name as the package in order to be usable without a object prefix i.e myType.mine If you name it with a different name for example :

    //package myType
    package object mainType {type mine = List[String]}
    

    it can be accessed with mainType.mine when you import "package"

    for more info : http://www.scala-lang.org/docu/files/packageobjects/packageobjects.html

    0 讨论(0)
  • 2021-02-01 12:26

    Will package objects work for you?

    From the article:

    Until 2.8, the only things you could put in a package were classes, traits, and standalone objects. These are by far the most common definitions that are placed at the top level of a package, but Scala 2.8 doesn't limit you to just those. Any kind of definition that you can put inside a class, you can also put at the top level of a package. If you have some helper method you'd like to be in scope for an entire package, go ahead and put it right at the top level of the package. To do so, you put the definitions in a package object. Each package is allowed to have one package object. Any definitions placed in a package object are considered members of the package itself.

    The package object scala has many types and values already, so I think you can use the same technique for your own types.

    0 讨论(0)
  • 2021-02-01 12:34

    I'm not sure what constitutes niceness in this case, but here are two options:

    Using a trait: (Scala's Selfless Trait Pattern)

    trait RestfulTypes {
      type Params = Map[String,String]
      //...
    }
    
    object MyRestService extends RestService with RestfulTypes { /* ... */ }
    

    Or just import the object's members, effectively using it like a package:

    import util.RestfulTypes._
    
    0 讨论(0)
提交回复
热议问题