Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Restrict class to trait and structural subtype in Scala

Tags:

scala

subtype

I need to restrict a Scala method parameter so that it implements both a trait and a structural subtype. How can I do this?

trait Foo
// ...
def someMethod[A <: Foo xxx { def close() }](resource: A)(block: A => Unit) {
  // ...
}

What do I put in place of xxx? I tried both extends and with, but got syntax errors.

Can it be done using a type definition for the structural subtype?

like image 957
Ralph Avatar asked Dec 09 '22 04:12

Ralph


2 Answers

Yes, you can use type for this:

type CanBeClosed = {def close()}

def someMethod[A <: Foo with CanBeClosed](resource: A)(block: A => Unit) {
  // ...
}

Recently I also wrote post about similar topic:

http://hacking-scala.posterous.com/composing-your-types-on-fly

like image 156
tenshi Avatar answered Dec 23 '22 19:12

tenshi


I'm actually not sure, if this is the same thing as what tenshi suggested, but it compiles, so try it out...

def someMethod[A <: Foo { def close() }](resource: A)(block: A => Unit) {
  // ...
}
like image 28
agilesteel Avatar answered Dec 23 '22 21:12

agilesteel