I want to define a trait that forces its subtypes to override say thetoString method.
Can I do that?
In the more generic case:
trait Old {
def foo: String = "oldFoo"
}
trait New {
//some statement which would result in "oldFoo" disappearing
}
trait New1 extend New {
def foo: String = "new1Foo"
} //should compile
trait New2 extend New //shouldn't compile
I don't think what you want to do is possible, but this workaround could work
trait Old {
def foo: String = "oldFoo"
}
trait New extends Old {
override final def foo: String = newFoo
def newFoo: String
}
class New1 extends New {
override def newFoo: String = "new1Foo"
} // Compiles
class New2 extends New // Don't compiles
trait NewExtra extends New // Compiles, but any sub class of NewExtra is required to implement newFoo
Related
When I extend traits I can choose which method implementation to use. Like here:
object Main {
def main(args: Array[String]): Unit = {
val c = new C
println(c.a)
println(c.b)
}
trait Parent {
def foo: String
}
trait A extends Parent {
override def foo = "from A"
}
trait B extends Parent {
override def foo = "from B"
}
class C extends A with B {
val b = super[A].foo
val a = super[B].foo
}
}
But if I want to do the same with self-types it's seems like it's not possible:
object Main {
def main(args: Array[String]): Unit = {
val c = new C with A with B
println(c.a)
println(c.b)
}
trait Parent {
def foo: String
}
trait A extends Parent {
override def foo = "from A"
}
trait B extends Parent {
override def foo = "from B"
}
class C {
self: A with B =>
val b = super[A].foo
val a = super[B].foo
}
}
This doesn't compile. Am I right and it's not possible? If I'm right, why is that and is there a workaround for it?
UPDATE:
Why do I needed in a first place? I was playing around with dependency injection using self-types instead of constructor injection. So I had a base trait Converter and child traits FooConverter and BarConverter. And I wanted to write it like that(which doesn't work of course):
object Main {
class Foo
class Bar
trait Converter[A] {
def convert(a: A): String
}
trait FooConverter extends Converter[Foo] {
override def convert(a: Foo): String = ???
}
trait BarConverter extends Converter[Bar] {
override def convert(a: Bar): String = ???
}
class Service {
this: Converter[Foo] with Converter[Bar] =>
def fooBar(f: Foo, b:Bar) = {
convert(f)
convert(b)
}
}
}
I thought it's because of generics, but it turned that it's not. So I was just wondering if it's possible to somehow invoke super method of chosen trait with self-types. Because with simple inheritance it's possible. As for my original problem I can write it like this and it will work:
object Main {
class Foo
class Bar
trait Converter[A] {
def convert(a: A): String
}
trait FooConverter extends Converter[Foo] {
override def convert(a: Foo): String = ???
}
trait BarConverter extends Converter[Bar] {
override def convert(a: Bar): String = ???
}
class Service {
this: FooConverter with BarConverter =>
def fooBar(f: Foo, b:Bar) = {
convert(f)
convert(b)
}
}
}
Probably tighter abstraction, but I'm not sure if it's bad for this kind of situation and if I need such broad abstraction like Converter[A] at all.
Calling super methods from already constructed type is impossible (you can do it only from the inside). In your example, you're trying to call foo on the instance self, which is constructed in runtime, so foo is virtual and could be overridden - compiler doesn't know which actual implementation is going to be called (formal vs real type problem). So technically - it's impossible to do what you want (call virtual method as a static one).
The naive hack is :
trait CC extends A with B {
val b = super[A].foo
val a = super[B].foo
}
class C {
self: CC =>
}
It basically provides encapsulation you want - you might wanna redefine a and b in class C as they're not going to be available (in type C itself) till you mix C with CC.
Note that in every example you provide (including my naive solution) - resulting val c has access to foo anyway and which exact foo is going to be called depends on how do you mix A and B (A with B or B with A). So, the only encapsulation you get is that type C itself isn't going to have foo method. This means that self-type gives you kind of a way to temporary close (make private) a method in "subclass" without violating LSP - but it's not the only way (see below).
Besides all of that, cake-injection that you're trying to implement is considered impractical by some authors. You might want to have a look at Thin Cake Pattern - as a remark, I successfully used something like this in real project (in combination with constructor injection).
I would implement your converter services this way:
class Foo
class Bar
trait Converter[A] {
def convert(a: A): String
}
object FooConverter1 extends Converter[Foo] {
override def convert(a: Foo): String = ???
}
object BarConverter1 extends Converter[Bar] {
override def convert(a: Bar): String = ???
}
trait FooBarConvertService {
def fooConverter: Converter[Foo]
def barConverter: Converter[Bar]
def fooBar(f: Foo, b: Bar) = {
fooConverter(f)
barConverter(b)
}
}
trait Converters {
def fooConverter: Converter[Foo] = FooConverter1
def barConverter: Converter[Bar] = BarConverter1
}
object App extends FooBarConvertService with Converters with ...
This allows you to change/mock converter implementation when putting it all together.
I'd also notice that Converter[Bar] is nothing else but Function1[Bar, String] or just Bar => String, so actually you don't need separate interface for that:
sealed trait FooBar //introduced it just to make types stronger, you can omit it if you prefer
class Foo extends FooBar
class Bar extends FooBar
trait FooBarConvertService {
type Converter[T <: FooBar] = T => String
def fooConverter: Converter[Foo]
def barConverter: Converter[Bar]
def fooBar(f: Foo, b: Bar) = {
fooConverter(f)
barConverter(b)
}
}
trait FooConverterProvider {
def fooConverter: Foo => String = ???
}
trait BarConverterProvider {
def barConverter: Bar => String = ???
}
object App
extends FooBarConvertService
with FooConverterProvider
with BarConverterProvider
You can also use def fooConverter(f: Foo): String = ??? instead def fooConverter: Foo => String = ???.
Talking about encapsulation - it's more weak here as you can access transitive dependencies, so if you really need it - use private[package] modifier.
Converters module:
package converters
trait FooBarConvertService {
type Converter[T <: FooBar] = T => String
private[converters] def fooConverter: Converter[Foo]
private[converters] def barConverter: Converter[Bar]
def fooBar(f: Foo, b: Bar) = {
fooConverter(f)
barConverter(b)
}
}
trait FooConverterProvider {
private[converters] def fooConverter: Foo => String = ???
}
trait BarConverterProvider {
private[converters] def barConverter: Bar => String = ???
}
Core module:
package client
import converters._
object App
extends FooBarConvertService
with FooConverterProvider
with BarConverterProvider
You can use objects object converters {...}; object client {...} instead of packages if you prefer.
This encapsulation is even stronger than self-type based one, as you can't access fooConverter/barConverter from the App object (in your example foo is still accessable from val c = new C with A with B):
client.App.fooBar(new Foo, new Bar) //OK
client.App.fooConverter
<console>:13: error: method fooConverter in trait FooConverterProvider cannot be accessed in object client.App
client.App.fooConverter
^
Keep in mind that self types are meant to allow you to require that any client code that uses the trait you are mixing in must also mix in another trait. In other words it is a way of declaring dependencies. But it is not classical inheritance. So when you say class C { self: A with B => } A and B actually are not there at the time. You have just defined that the client code has to mix in A and B in order to then mix in C.
But for your specific use case, it seems like you can accomplish the same goal with something like this code. In other words first create a third trait and then extend it into a specific class.
object DoubleSelfType extends App {
val c = new DoubleFoo
println(c.a)
println(c.b)
trait Parent {
def foo: String
}
trait A extends Parent {
override def foo = "from A"
}
trait B extends Parent {
override def foo = "from B"
}
trait C {
self: A with B =>
val a = ""
val b = ""
}
class DoubleFoo extends C with A with B {
override val b = super[A].foo
override val a = super[B].foo
}
}
abstract class SuperClass {
def method() = this
}
class SubClass1 extends SuperClass {
def method1() = this
}
class SubClass2 extends SuperClass {
def method2() = this
}
val obj1 = new SubClass1()
obj1.method1().method() // this is ok
val obj2 = new SubClass2()
obj2.method().method2() // this is not ok, as method returns a SuperClass,
// which has no method named method2
So how to make the method return the subclass type so I can chain the operation in any order.
So far what I can think is to follow something like
abstract class SuperClass[T <: SuperClass[T]]
but I don't know how to continue that.
Something like this should work:
abstract class SuperClass {
def method(): this.type = this
}
I find the following approach works as well:
abstract class SuperClass[T <: SuperClass[T]] {
def method(): T = this.asInstanceOf[T]
}
class SubClass extends SuperClass[SubClass] {
def method1() = this
}
val obj = new SubClass()
obj.method1().method()
obj.method().method1()
Is there a way in scala to use a method m in the implementation of the method overriding the same method m?
As an example here is what I tried (note that toUpperCase is not implemented):
abstract class Person {
def greet: String
}
class EnglishMan extends Person {
abstract override def greet: String =
{
return "hello"
}
}
trait Angry extends Person {
abstract override def greet: String =
{
return toUpperCase(greet)
}
Is this what you want?
scala> trait Person { def greet: String }
defined trait Person
scala> class EnglishMan extends Person { def greet = "hello" }
defined class EnglishMan
scala> class Angry extends EnglishMan { override def greet = super.greet.toUpperCase }
defined class Angry
scala>
scala> new EnglishMan().greet
res3: String = hello
scala> new Angry().greet
res4: String = HELLO
Note that trait Person is completely irrelevant to this exercise. You can invoke your superclass' methods (even when overriding that very method), but you can't have 2 methods on the same scope with the same name (that would be ambiguous for the compiler).
I have a trait and a class that extends the trait. I can use the methods from the trait as follows:
trait A {
def a = ""
}
class B(s: String) extends A {
def b = a
}
However, when I use the trait's method in the constructor like this:
trait A {
def a = ""
}
class B(s: String) extends A {
def this() = this(a)
}
then the following error appears:
error: not found: value a
Is there some way to define default parameters for the construction of classes in the trait?
EDIT: To clarify the purpose: There is the akka-testkit:
class TestKit(_system: ActorSystem) extends { implicit val system = _system }
And each test looks like this:
class B(_system: ActorSystem) extends TestKit(_system) with A with ... {
def this() = this(actorSystem)
...
}
because I want to create common creation of the ActorSystem in A:
trait A {
val conf = ...
def actorSystem = ActorSystem("MySpec", conf)
...
}
It's a little bit tricky because of Scala initialization order. The simplest solution I found is to define a companion object for your class B with apply as factory method:
trait A {
def a = "aaaa"
}
class B(s: String) {
println(s)
}
object B extends A {
def apply() = new B(a)
def apply(s: String) = new B(s)
}
I have this:
case class Aaa() extends NClass {
def method1() = println("method1")
}
object Aaa extends NCompanion {
def method2() = println("method2")
}
I would like to implement something like the following pseudo code:
abstract class Xxx[T] {
// All the trash code of reflection/implicit should be in this class only
instance = new T()
companion = T
instance.method1()
companion.method2()
}
To use like this:
class Yyy extends Xxx[Aaa] {}
How can I implement this? It is better if I could use the new Scala Reflection API. Thanks in advance!
For now I am using a solution avoiding get the companion type with generics:
abstract class Xxx[T <: NClass[T], O <: NCompanion[T]](implicit tag: TypeTag[T]) {
def getInstance(): T
def getCompanion(): O
val classOfT = typeTag[T].mirror.runtimeClass(typeOf[T])
val className = classOfT.getName
println(s"$className")
val t = getInstance()
val manager = getCompanion()
}
Usage:
class Yyy extends Xxx[Aaa, Aaa.type] {
override def getInstance: Aaa = {
return new Aaa()
}
override def getCompanion: Aaa.type = {
return Aaa
}
}