我知道我可以在 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/