Srinivas
Srinivas

Reputation: 2098

Abstract structural types implementation

I am trying to understand abstract structural types. Suppose I have a trait

trait Test {

  type Foo = String => Unit

  def printFoo(s : Foo) = {
    println(s)
  }
}

and a simple function

val foo : String => Unit = (s : String) => println(s)

How will I implement this function in a class? When I try

  val s = new Test {
    override type Foo = String => Unit
  }

and try to implement

s.printFoo(foo("Test"))

It does not work.

Upvotes: 0

Views: 74

Answers (1)

user3725190
user3725190

Reputation: 343

Since your method printFoo gets a lambda, you are printing the function object. One way to solve your issue is by providing multiple parameter lists:

trait Test {

  type Foo = String => Unit

  def printFoo(f: Foo)(s: String) = {
    f(s)
  }
}

val foo : String => Unit = (s : String) => println(s)

val s = new Test {
  override type Foo = String => Unit
}

s.printFoo(foo)("something")

// or reuse it:
val doFoo: String => Unit = s.printFoo(foo)
doFoo("something A...")
doFoo("something B...")

Upvotes: 1

Related Questions