class - 有没有静态鸭子类型(duck typing)的语言?

标签 class interface language-design duck-typing static-typing

Can I specify interfaces when I declare a member?

在考虑了这个问题一段时间后,我突然想到静态鸭子类型(duck typing)的语言可能真的有效。为什么预定义的类不能在编译时绑定(bind)到接口(interface)?例子:

public interface IMyInterface
{
  public void MyMethod();
}

public class MyClass  //Does not explicitly implement IMyInterface
{
  public void MyMethod()  //But contains a compatible method definition
  {
    Console.WriteLine("Hello, world!");
  }
}

...

public void CallMyMethod(IMyInterface m)
{
  m.MyMethod();
}

...

MyClass obj = new MyClass();
CallMyMethod(obj);     // Automatically recognize that MyClass "fits" 
                       // MyInterface, and force a type-cast.

你知道任何支持这种功能的语言吗?它对 Java 或 C# 有帮助吗?它在某些方面存在根本性缺陷吗?我知道你可以继承 MyClass 并实现接口(interface)或使用 Adapter 设计模式来完成同样的事情,但这些方法看起来像是不必要的样板代码。

最佳答案

Crystal是一种静态鸭子类型(duck typing)的语言。 Example :

def add(x, y)
  x + y
end

add(true, false)

调用 add导致此编译错误:
Error in foo.cr:6: instantiating 'add(Bool, Bool)'

add(true, false)
^~~

in foo.cr:2: undefined method '+' for Bool

  x + y
    ^

关于class - 有没有静态鸭子类型(duck typing)的语言?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/289106/

相关文章:

c# - 查找接口(interface)实例背后的具体类型

c++ - 如何从类队列中获取 'push' 和 'pop'?

c++ - 声明类类型的数组(Borland C++ 有问题)

css 伪类不显示或悬停

typescript - 在 Vuejs 类 Component 中声明 typescript 接口(interface) Props

java - 奇怪的接口(interface)实现

c - 为什么指针 (*) 和数组 ([]) 符号绑定(bind)到变量名而不是键入变量声明?

c++ - 通用引用的语法

c - 为构建你自己的 Lisp 书滚动一个解析器?

c++ - 尝试在类定义中声明数组时出错