在Scala中,为什么类型注释必须遵循函数参数?为什么编译器不能推断函数参数类型? [英] In Scala, why does a type annotation must follow for the function parameters ? Why does the compiler not infer the function parameter types?

查看:155
本文介绍了在Scala中,为什么类型注释必须遵循函数参数?为什么编译器不能推断函数参数类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的问题,为什么Scala编译器不能自行推断函数参数类型?

解决方案


像Haskell这样的函数式编程语言可以推出几乎所有类型的
,因为它们可以执行全局类型推断。 Scala不能
这样做,部分原因是Scala必须支持子类型多态
(继承),这使得类型推断更加困难。这是
规则的总结,用于在Scala中需要显式类型注释
时。


当需要显式类型注解时

实际上,您必须为以下情况提供显式类型注释:




  • 一个可变的var或不可变的val声明,您不需要赋值(例如,像val book这样的类中的抽象声明:String,var count: Int


  • 所有方法参数(例如def deposit(amount:Money)= {...})。
    在以下情况下返回类型的方法:
    $ b $ 1当你在方法中显式调用return时(甚至在结束时)。



    2)当一个方法是递归的。 3)当两个或多个方法被重载(具有相同的名称)并且其中一个调用另一个时,调用方法需要一个返回类型注释。



    4)当推断返回类型比您想要的更通用时,例如Any。




来源 Programming Scala ,第二版 - O'Reilly Media

I have a simple question, why is the Scala compiler not able to infer the function parameter types by itself ?

解决方案

Some functional programming languages, like Haskell, can infer almost all types, because they can perform global type inference. Scala can’t do this, in part because Scala has to support subtype polymorphism (inheritance), which makes type inference much harder. Here is a summary of the rules for when explicit type annotations are required in Scala.

When Explicit Type Annotations Are Required

In practical terms, you have to provide explicit type annotations for the following situations:

  • A mutable var or immutable val declaration where you don’t assign a value, (e.g., abstract declarations in a class like val book: String, var count: Int

  • All method parameters (e.g., def deposit(amount: Money) = {…}).

  • Method return types in the following cases:

    1)When you explicitly call return in a method (even at the end).

    2)When a method is recursive.

    3)When two or more methods are overloaded (have the same name) and one of them calls another; the calling method needs a return type annotation.

    4)When the inferred return type would be more general than you intended, e.g., Any.

Source Programming Scala, 2nd Edition - O'Reilly Media

这篇关于在Scala中,为什么类型注释必须遵循函数参数?为什么编译器不能推断函数参数类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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