Scala common features

I have an abstract class

abstract class Foo {
  def foo(a: Int): Int
  ...
}

// Usage
new Foo {
  def foo(a: Int) = {
    println("Foo")
    a
  }
}

I often see a companion object to make it a little less verbose for callers (like the Play framework).

object Foo {
  def apply(f: Int => Int) = new Foo {
    def foo(a: Int) = f(a)
  }
}

// Usage
Foo { a =>
  println("Foo")
  a
}

But suppose I make a generic method

abstract class Foo {
  def foo(a: T): T
  ...
}

// Usage
new Foo {
  def foo(a: T) = {
    println("Foo")
    a
  }
}

Can I use a companion object, i.e. Can I apply general type parameters to a function, and not to a method or class?

+4
source share
1 answer

Yes, you can do this by emulating polymorphism rank 2. Based on this article, you can:

trait ~>[F[_],G[_]] {
  def apply[A](a: F[A]): G[A]
}

type Id[A] = A

abstract class Foo {
  def foo[T](a: T): T
}

object Foo {
  def apply(f: Id ~> Id) = new Foo {
    def foo[T](a: T): T = f(a)
  }
}

val fun = new (Id ~> Id) { def apply[T](a: T): T = { println("Foo"); a } }
val foo = Foo(fun)
foo.foo(1)
foo.foo("String")
+5
source

All Articles