I understand I can define duck typing in generics
as following
trait MyTrait[A <: {def someMethod(key: String): String}]
However I don't want to specify that whole big string
in my trait
definition.
How can I split this to two (what I wish I could have):
type A = B <: {def someMethod(key: String): String}
trait MyTrait[A]
You can do:
type B = { def someMethod(key: String): String }
trait MyTrait[A <: B]
In fact, some Scala style guides recommend this breakdown when the structural type would have more than 50 characters. 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
You cannot assign the type bound A <: B
itself to a type alias, since it is not a type, but a constraint on the generic parameter of MyTrait
. You can read more about type bounds here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With