in scala define generic type based on duck typing?
Asked Answered
R

1

5

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]
Rosamariarosamond answered 31/3, 2015 at 12:22 Comment(0)
G
9

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.

Gorton answered 31/3, 2015 at 12:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.