gpt4 book ai didi

Scala 类型关键字 : how best to use it across multiple classes

转载 作者:行者123 更新时间:2023-12-03 00:11:26 25 4
gpt4 key购买 nike

在写完 Haskell 后回到 Scala,我开始使用 type 关键字来使我的类定义更具可读性,例如:

type RestfulParams = Map[String, String]
def canonicalize(params: RestfulParams): String = { ... }

我遇到的麻烦是这些类型定义需要存在于类或对象中——它们不像 Haskell 中那样是“一等公民”。如果我尝试在类或对象之外定义类型,我会得到编译器预期的类或对象定义

我的问题是如何在包中的多个类和对象中使用这些类型?我现在所做的看起来很丑陋:

object RestfulTypes { type RestfulParams = Map[String, String] etc }

然后在另一个类文件中:

import utils.{RestfulTypes => RT}
def get(resource: String, params: RT.RestfulParams): String = { ... }

是否有更好的方法来做到这一点 - 顺便说一句,Scala 专家认为类型只能在类/对象内定义是好事还是坏事?

最佳答案

威尔package objects为你工作吗?

摘自文章:

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.

package object scala已经有很多类型和值,所以我认为您可以对自己的类型使用相同的技术。

关于Scala 类型关键字 : how best to use it across multiple classes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7441277/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com