加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Scala是否有类似于C#的显式接口实现?

发布时间:2020-12-16 10:04:11 所属栏目:安全 来源:网络整理
导读:在C#中,您可以明确地实现接口.然后,只能通过将接口作为其静态类型的变量来调用明确实现的方法.这允许您避免名称/返回类型冲突,并根据其静态类型提供相同方法的不同实现. 例如: interface IFoo{ int DoSomething();}interface IBar{ string DoSomething();}c
在C#中,您可以明确地实现接口.然后,只能通过将接口作为其静态类型的变量来调用明确实现的方法.这允许您避免名称/返回类型冲突,并根据其静态类型提供相同方法的不同实现.

例如:

interface IFoo
{
    int DoSomething();
}

interface IBar
{
    string DoSomething();
}

class Impl : IFoo,IBar
{
    int IFoo.DoSomething() { /* Implementation for IFoo */ }
    string IBar.DoSomething() { /* A different implementation for IBar */ }
    public void DoSomething() { /* Yet another implementation for Impl */ }
}

你会如何处理Scala中的这种情况:

trait Foo {
    def doSomething(): Int
}

trait Bar {
    def doSomething(): String
}

class Impl extends Foo with Bar {
    /* only one "doSomething()" visible here (that of Bar?) */
    /* what now... ? */
}

解决方法

如果您只是想让您的类遵循两个独立的不兼容接口,那么您必须编写包装器.例如,

implicit case class ImplAsFoo(impl: Impl) extends Foo {
  def asFoo = this
  def doSomething: Int = 5
}

现在你可以

impl.asFoo

在使用现场切换到Foo包装.

但是,在某些情况下,使用类型类模式代替提供可插入功能可能更自然:

trait IFoo[A] { def doSomething: Int }
trait IBar[A] { def doSomething: String }

// These need to be companions so :paste if you're using REPL
class Impl { def doSomething { println("Hey!") } }
object Impl {
  implicit object FooImpl extends IFoo[Impl] { def doSomething = 5 }
  implicit object BarImpl extends IBar[Impl] { def doSomething = "salmon" }
}

def needsFoo[A <: Impl: IFoo](a: A) = implicitly[IFoo[Impl]].doSomething

scala> needsFoo(new Impl)
res1: Int = 5

scala> (new Impl).doSomething
Hey!

它并不完全相同,但这也解决了在没有命名方案绊倒你的情况下实现不同实现的问题. (如果您需要使用impl对象执行某些操作,则将其作为处理该情况的隐式对象中的参数传递.)

如果你已经有了特质,那么当然这对你没有帮助.但是当你从头开始设计时,你可能会尝试输入类,而不是使用不兼容的方法.

最后,如果你无法帮助将一堆无用的东西混杂在一起,你需要选择Foos,你必须发明更多精心设计的方案,如下:

trait CanBeFoo { def asFoo: Foo }
trait Foo { def doSomething: Int }

// :paste these two together
class Impl extends CanBeFoo {
  def doSomething { println("Ho!") } 
  def asFoo = ImplAsFoo(this)
}
case class ImplAsFoo(impl: Impl) extends Foo {
  def doSomething = 6
}

val myList = List("salmon",new Impl,new Foo { def doSomething = 4 })
def doIt(f: Foo) { println(f.doSomething) }
myList.foreach {
  case f: Foo => doIt(f)
  case cf: CanBeFoo => doIt(cf.asFoo)
  case _ => println("nuh-uh")
}

// Produces
// nuh-uh
// 6
// 4

您可能更喜欢中间地图:

myList.map{ case cf: CanBeFoo => cf.asFoo; case x => x }.foreach{
  case f: Foo => println(f.doSomething)
  case _ => println("nuh-uh")
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读