Scala中的类型推断
Scala类型接口 (Scala Type Interface)
Type interface in Scala is used to make the type declaration optional and handle all type mismatch exceptions if any occurred.
Scala中的Type接口用于使类型声明为可选,并处理所有类型不匹配异常(如果发生)。
This capability of compiler makes it easier for programmers to write code. As the declaration of the data type can be left as compilers work to detect the data type.
编译器的这种功能使程序员更容易编写代码。 由于可以保留数据类型的声明,因此编译器会检测数据类型。
Let’s take an example of a Scala program that declares variables with their data type,
让我们举一个Scala程序的示例,该程序以其数据类型声明变量 ,
object MyClass {
def main(args: Array[String]) {
var data : Double = 34.45;
println("The data is "+ data +" and data type is "+data.getClass);
}
}
Output
输出量
The data is 34.45 and data type is double
Now, let’s see the type inference in action,
现在,让我们看看实际的类型推断,
object MyClass {
def main(args: Array[String]) {
var data = 34.45;
println("The data is "+ data +" and datatype is "+data.getClass);
}
}
Output
输出量
The data is 34.45 and datatype is double
As you can observe, the output of both codes is the same. If the programmer does not provide the data type of the variable the compiler will do the work and give the data a type based on the data that is stored in it.
如您所见,这两个代码的输出是相同的。 如果程序员不提供变量的数据类型,则编译器将进行工作并根据存储在其中的数据为数据提供类型。
函数中的Scala类型推断 (Scala type inference in function)
We have seen the type inference for variables. Now, let’s see type inference in function. In type inference for functions, the return type of functions is omitted also the return keyword is eliminated.
我们已经看到了变量的类型推断 。 现在,让我们看看function中的类型推断 。 在函数的类型推断中 ,将省略函数的返回类型,并消除return关键字。
Let’s see an example of type inference in function,
让我们看一个函数中类型推断的例子,
object MyClass {
def multiplier(a : Int , b:Int) ={
var product = a*b;
product;
}
def main(args: Array[String]) {
var data = 34.45;
println("The product of numbers is "+ multiplier(34 , 54));
}
}
Output
输出量
The product of numbers is 1836
In the case of type inference, we need to omit the return keyword also. Otherwise, an error is returned by the compiler.
在类型推断的情况下,我们还需要省略return关键字。 否则,编译器将返回错误。
翻译自: https://www.includehelp.com/scala/type-inference.aspx
还没有评论,来说两句吧...