强制多态参数属于同一类型

时间:2017-11-13 23:22:35

标签: scala polymorphism

在下面的方法中,我希望设置函数的类型 强制package *; import java.util.Scanner; public class * { // n = limit of inputs private static final int n = 10; static Scanner kb = new Scanner(System.in); public static void main(String[] args) { //nkb = number from keyboard int [] nkb = new int[n]; // in = number of length int in = nkb.length; //for input user for (int i = 0; i < n; i ++){ System.out.println("Writte a number: "); nkb[i] = kb.nextInt(); }//end for for (int i = 0; i < n; i ++){ System.out.println("In these position "+i+" now we have these number: "+nkb[in-1-i]); }//end for reverse }//end method }//end class from是LexicalDate的相同类型。即它们必须都是to或两者都必须是Day

目前,Hourfrom可以作为不同类型的LexicalDate传递。

tofrom是否可以在编译级强制始终与to的类型相同?

LexicalDate

1 个答案:

答案 0 :(得分:3)

您正在寻找的是广义类型约束=:=,它要求编译器能够证明两种类型是相等的。对于您的情况,=:=可以如下使用(特别是,请注意queryDate方法的隐式参数列表):

scala> def queryDate[A <: LexicalDate, B <: LexicalDate](id: Long, from: A, to: B)(implicit ev: A =:= B) { }
queryDate: [A <: LexicalDate, B <: LexicalDate](id: Long, from: A, to: B)(implicit ev: A =:= B)Unit

scala> queryDate(10, Day, Day)

scala> queryDate(10, Hour, Hour)

scala> queryDate(10, Day, Hour)
<console>:15: error: Cannot prove that Day.type =:= Hour.type.
       queryDate(10, Day, Hour)
                ^

scala> queryDate(10, Hour, Day)
<console>:15: error: Cannot prove that Hour.type =:= Day.type.
       queryDate(10, Hour, Day)
                ^

有关广义类型约束的一般描述,请参阅以下链接: