scala

Scala Generics, exclude type


I need to have a function like:

def foobar[A](cb: Int => A)

I would like to check that A is not a Future.

Is this possible?

@LuisMiguelMejíaSuárez this is my code based on your link:

def closeOnExit[A <: {def close() : Unit}, B](closeable: A)
                                                (cb: A => B)
                                                (implicit e: B =!= Future[_]): B = {
   try {
      cb(closeable)
   } finally {
      closeable.close()
   }
}

No error was generated with: closeOnExit(new FileOutputStream("deleteme.txt")) {is => Future.successful(1)}

On the case of:

def foobar[A, B](a:A, b:B)(implicit e: A =!= B): (A, B) = (a, b)
foobar(1, 2)

You already find an error


Solution

  • My solution

      sealed class IsNotFuture[A]
    
      object IsNotFuture {
        // the fact that we have 2 implicit functions for type Future will fail to compile
        implicit def isFuture1[B <: Future[_]]: IsNotFuture[B] = ???
        implicit def isFuture2[B <: Future[_]]: IsNotFuture[B] = ???
    
        // all the rest compile
        implicit def isNotFuture[B]: IsNotFuture[B] = new IsNotFuture[B]
      }