user79074
user79074

Reputation: 5300

More aesthetic way to instantiate an anonymous implementation of a trait

Say I have a function that expects an instance of a trait:

trait MyTrait[T] {
  def f1: T
  def f2(t: T): Unit
}

def foo[T](t: MyTrait[T]) { ... }

Now, anywhere I call this function I need to use the following syntax:

val x = foo[String](new MyTrait[String] {
  def f1 = "Hello"
  def f2(str: String) = { ... }
}

I am wondering if there is another way I can achieve this to make my usages simpler and more aesthetic? Ideally I would like to have the following usage:

val x = foo() {
  def f1 = "Hello"
  def f2(str: String) = { ... }
}

Upvotes: 0

Views: 355

Answers (2)

Nabil A.
Nabil A.

Reputation: 3400

If you use this trait anonymous everywhere like you described, throw it away!
Instead make the function look like

def foo[T](f1: T,  f2: T => Unit)  

so you can call it like

foo("Hello", (myString:String) =>  { } )

Upvotes: 3

Ben
Ben

Reputation: 1474

An alternative to Nabil A.'s answer, if you want to keep the trait, is to subclass it using a case class that takes f1 and (a function describing) f2 as parameters:

case class MyClass[T](f1: T, _f2: T => Unit) extends MyTrait[T] {
  def f2(t: T) = _f2(t)
}

You can then instantiate it as:

foo(MyClass[String]("hello", str => {...}))

Upvotes: 1

Related Questions