oleber
oleber

Reputation: 1079

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

Upvotes: 2

Views: 604

Answers (2)

Hartmut Pfarr
Hartmut Pfarr

Reputation: 6139

Let's try

import scala.concurrent.Future
import scala.reflect.runtime.universe._

object Scala_Generics_Excelude_Type {

   def main(args: Array[String]): Unit = {

      new Scala_Generics_Excelude_Type[Int].cb(i => 1) // ok

      new Scala_Generics_Excelude_Type[String].cb(i => "1") // ok

      new Scala_Generics_Excelude_Type[Future[String]].cb(i => null) 
                                       // Exception: No future please

   }
}

class Scala_Generics_Excelude_Type[T: TypeTag] {
   def cb(cb: Int => T) = {
      if (typeOf[T].typeSymbol == typeOf[Future[Any]].typeSymbol) 
                throw new Exception("No future please")
   }
}

UPDATE 2018-11-25

is needed:

libraryDependencies += "org.scala-lang" % "scala-reflect" % scalaVersion.value

Upvotes: 0

oleber
oleber

Reputation: 1079

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]
  }

Upvotes: 2

Related Questions