简体   繁体   English

Haskell 在 Scala 中的新类型

[英]Haskell's newtypes in Scala

In Haskell we can declare newtypes to reduce dynamic memory allocations and create type-safe APIs.在 Haskell 中,我们可以声明新类型以减少动态 memory 分配并创建类型安全的 API。

newtype Username String = Username String
  deriving (Eq, Ord)

newtype works only with data types which have single constructor with single argument. newtype 仅适用于具有单个构造函数和单个参数的数据类型。 Is there something similar to newtype in Scala? Scala 中是否有类似于 newtype 的东西?

Example:例子:

case class Username(username: String)

for username we could've write something like this in Scala:对于用户名,我们可以在 Scala 中编写类似这样的内容:

newtype Username(username: String)

The equivalent to Haskell's newtype areOpaque Type Aliases in Scala 3:与 Haskell 的新类型等效的是newtype 3 中的不透明类型别名

opaque type Username = String

It's basically a type alias … but opaque.它基本上是一个type别名……但不透明。 Just like it says on the cover.就像封面上说的那样。

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

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