scala - 在 scala 中基于鸭子类型定义泛型类型?

标签 scala generics structural-typing

我知道我可以在 generics 中定义鸭子类型。如下

trait MyTrait[A <: {def someMethod(key: String): String}]

但是我不想指定整个大 string在我的trait定义。

我怎样才能把它分成两个( 我希望我能拥有的 ):
type A = B <: {def someMethod(key: String): String}

trait MyTrait[A]

最佳答案

你可以做:

type B = { def someMethod(key: String): String }
trait MyTrait[A <: B]

事实上,当结构类型超过 50 个字符时,一些 Scala 风格指南建议使用这种分割。 Here's one from the Scala docs :

Structural types should be declared on a single line if they are less than 50 characters in length. Otherwise, they should be split across multiple lines and (usually) assigned to their own type alias



您不能分配类型绑定(bind) A <: B自身为类型别名,因为它不是类型,而是对 MyTrait 的泛型参数的约束.你可以阅读更多关于类型界限 here .

关于scala - 在 scala 中基于鸭子类型定义泛型类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29368590/

相关文章:

Scala:对象初始化程序中的并行收集导致程序挂起

scala - LiftWeb 框架 - 覆盖 LiftRules.sessionInactivityTimeout

java - 如何将 Object 类型转换为 List<Object> 类型?

scala - 有没有办法用中缀表示法调用scala方法(具有类型参数)

scala - 如何使用带有通用参数的结构类型?

scala - scala中光滑的错误

java - 将 Excel 文件流式传输到 S3 内存中?为什么 ZipOutputStream 上的 ByteOutputStream.reset() 会导致写入无法工作?

c# - C# 泛型是否支持类型签名约束?

java - 集合的非泛型子类的构造函数

scala - 从宏中获取具有匿名类方法的结构类型