Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

An abstract signature for "without" some type

Tags:

mixins

scala

I want a method of a type to return the type it is mixed into. E.g., something in the spirit of the following:

trait A {
  def withoutA: this.type without A
}

So in case of type A with B with C, the method withoutA would have a signature B with C, in case of A with D - just D.

Is this achievable and how if it is?

Here's an example of how it could be used:

trait Limit {
  def limit(a: Int): this.type without Limit
}
trait Offset {
  def offset(a: Int): this.type without Offset
}
val sqlBuilder = new Limit with Offset { ... }
sqlBuilder.limit(2).offset(4) // valid code
sqlBuilder.offset(4).limit(2) // valid code
sqlBuilder.limit(2).limit(4) // invalid code
like image 569
Nikita Volkov Avatar asked Nov 11 '22 14:11

Nikita Volkov


1 Answers

A stab in the dark here, but the type Negation as defined by shapeless might work here.

type ¬[A] = A => Nothing

trait A {
  def withoutA: this.type with ¬[A]
}

Without access to a REPL right now, I haven't had the chance to test this though. I'd also be interested to know the use-case.

UPDATE:

If what you really want is a builder that progressively reduces the operations available as you use them, then phantom types and the type-safe builder pattern come to the rescue:

http://james-iry.blogspot.co.uk/2010/10/phantom-types-in-haskell-and-scala.html

http://blog.rafaelferreira.net/2008/07/type-safe-builder-pattern-in-scala.html

You might want to update the title of the question as well, so it's easier for others to find :)

like image 93
Kevin Wright Avatar answered Nov 14 '22 22:11

Kevin Wright