0

Is there a way to "program to interface" in scala?

I am new in Scala. I have a "trait" in scala and many classes extending that trait. I am looking for a way on how to use the interface instead of the class directly.

Currently, I am doing :

val clazz = new MyClass() 

where MyClass is extended from a trait.

I am looking for a way to return the interface as an instance from the factory mathods for generating classes. Is there a way?

4
  • 1
    Widening conversions in Scala work just like they would in Java. If MyClass implements a trait Foobar and your method has return type Foobar, you can return clazz just fine. Commented Aug 17, 2018 at 15:31
  • 1
    calling asInstanceOf[MyClass] breaks type safety and defeats the purpose of "program to interface" Commented Aug 17, 2018 at 16:03
  • Your question is unclear. You are talking about "programming to an interface", but in your example, you cast the value to a concrete subclass type using asInstanceOf, which is the exact opposite of programming to an interface. Commented Aug 17, 2018 at 16:03
  • Also, it is not clear what you mean by "I am looking for a way to return the interface as an instance from the factory mathods for generating classes." You can only return objects from methods. But traits aren't objects, therefore you cannot return a trait from a factory method. (Well, you can obtain a reflective proxy for a trait using the Scala reflection API and return that …) Commented Aug 17, 2018 at 16:06

1 Answer 1

1

You can always just request the type of the interface:

val clazz: MyInterf = new MyClass()

If you really want to hide the implementation, one approach is to create a companion for the trait:

trait MyInterf {
  ...
}

class MyClass extends MyInterf {
  ...
}

object MyInterf {
  def create: MyIntef = new MyClass()
}

// calling code
val impl = MyInterf.create
Sign up to request clarification or add additional context in comments.

2 Comments

If I have 2 classes implementing this interface, how to change the create method to return the right instance based on the requirement? I am trying to understand how to implement the facetory mathods
based on what requirement? If it's just during creation, you can pass a parameter to the create method. Beyond creation, if your calling code needs to be aware of what class is providing the implementation, then you're not really "programming to the interface"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.