有没有静态的鸭式语言? [英] Are there any static duck-typed languages?

查看:115
本文介绍了有没有静态的鸭式语言?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以在声明成员时指定接口?

在考虑这个问题一段时间后,我发现静态鸭式语言实际上可能工作。为什么在编译时不能将预定义类绑定到接口?示例:

After thinking about this question for a while, it occurred to me that a static-duck-typed language might actually work. Why can't predefined classes be bound to an interface at compile time? Example:

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和实现接口或使用适配器设计模式来完成同样的事情,但这些方法看起来像不必要的样板代码。

Do you know of any languages that support such a feature? Would it be helpful in Java or C#? Is it fundamentally flawed in some way? I understand you could subclass MyClass and implement the interface or use the Adapter design pattern to accomplish the same thing, but those approaches just seem like unnecessary boilerplate code.

推荐答案

根据定义,静态类型语言在编译时检查类型,而不是运行时。上述系统的一个明显问题是编译器在程序编译时而不是在运行时检查类型。

Statically-typed languages, by definition, check types at compile time, not run time. One of the obvious problems with the system described above is that the compiler is going to check types when the program is compiled, not at run time.

现在,你可以构建更多的智能进入编译器,所以它可以派生类型,而不是让程序员显式地声明类型;编译器可能能够看到 MyClass 实现了一个 MyMethod()方法,并相应地处理这种情况,没有需要显式声明接口(如你所建议)。这样的编译器可以使用类型推断,例如 Hindley-Milner

Now, you could build more intelligence into the compiler so it could derive types, rather than having the programmer explicitly declare types; the compiler might be able to see that MyClass implements a MyMethod() method, and handle this case accordingly, without the need to explicitly declare interfaces (as you suggest). Such a compiler could utilize type inference, such as Hindley-Milner.

当然,一些静态类型的语言像Haskell已经做了类似于你建议的事情; Haskell编译器能够推断类型(大部分时间),而不需要显式声明它们。但显然,Java / C#没有这个能力。

Of course, some statically typed languages like Haskell already do something similar to what you suggest; the Haskell compiler is able to infer types (most of the time) without the need to explicitly declare them. But obviously, Java/C# don't have this ability.

这篇关于有没有静态的鸭式语言?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆