Can I specialize function type parameters in Scala, as I can, using the C ++ template specialization?

I want to write a function that behaves differently depending on its type parameter. The following is a simple example of what I want:

def f[Int] = "I'm an int"
def f[Float] = "I'm a float"
def f[Burger] = "You want fries with that?"

Is this possible in Scala or do I need some work?

+5
source share
3 answers

Not directly; the usual way you do this in Scala is with a type class.

trait FAble[T] { def doF: String }
object FAble {
  implicit val fInt = new FAble[Int] { def doF = "I'm an int" }
  implicit val fFloat = new FAble[Float] { def doF = "I'm a float" }
  implicit val fBurger = new FAble[Burger] { def doF = "You want fries?" }
}

def f[T](implicit ev: FAble[T]) = ev.doF
// or
def f[T: FAble] = implicitly[FAble[T]].doF

, - ( implicit def val s), , , .

, , - , Scala generics (@specialized , , ). " , Int , , , , ".

+14

:

def f[T](t:T)(implicit ev: T<:<Float) {

// float version 

}

def f[T](t:T)(implicit ev: T<:<Int) {

// int version 

}

+2

You can see the macros: http://scalamacros.org/ . Macros are custom functions that are executed at compile time and can dynamically generate code based on compilation time calculations.

+1
source

All Articles