2017-08-16 75 views
1

一个说我有这样一个特点:特质实现都必须实现的两种方法

trait Truthy { 
    def isFalse = !isTrue 
    def isTrue = !isFalse 
} 

显然,这将无限递归如果扩展特质类不实现isTrue也不isFalse,其中一人被调用。

我可以离开要么isTrueisFalse没有默认实现,但后来我不得不挑一些实现可能有一个很自然的isTrue实施而另一些可能有一种天然的isFalse之一。

是否有办法强制扩展类来实现两种方法之一而不偏向其中之一?

+1

我想这个问题是一个简化,因为简单的方法将是'最终def isFalse =!isTrue'在特质 – cchantep

+0

这是行不通的,因为它不允许提供'isFalse'的实现一个子类。 –

回答

2

在Scala中没有办法强制执行这样的约束,但是可以使用多个特征来解决问题;例如: -

trait Truthy { 
    def isFalse: Boolean 
    def isTrue: Boolean 
} 

object Truthy { 
    trait DeriveIsFalse { 
    this: Truthy => 

    def isFalse = !isTrue 
    } 

    trait DeriveIsTrue { 
    this: Truthy => 

    def isTrue = !isFalse 
    } 
} 

然后你可以使用它作为:

class MyImplementation extends Truthy with Truthy.DeriveIsTrue { 
    def isFalse = someMeaningfulImplementation() 
} 

这是一种方式,但如果使用多个性状,肯定有其他的。

相关问题