简体   繁体   English

如何使scala类型更高的类型起作用

[英]how to get scala higher-kinded type to work

I'm trying to improve my understanding of higher-kinded type in Scala. 我正在努力提高对Scala中更高种类的类型的理解。 While I went back to the basic, i got stuck on the following: 回到基础知识时,我坚持以下几点:

 def fooList[A <: Int](x: List[A]): List[A] = x.map{ e => e + 1 }

The Scala compiler does not accept it which, i do not understand. 我不理解,Scala编译器不接受它。 "A" must be a subclass of Int. “ A”必须是Int的子类。 hence whatever type under Int that shall be passed there should work. 因此,在Int下传递的任何类型都应该起作用。 Why does it complain? 为什么会抱怨? Can someone advise me here ? 有人可以在这里建议我吗?

M 中号

A really must be an Int in this case, because you can't create a sub-class of Int , but the compiler doesn't seem to want to prove that. 在这种情况下, A实际上必须是Int ,因为您不能创建Int的子类,但编译器似乎不想证明这一点。 That aside, since A <: Int , the + method of Int returns an Int . 的是,除了,因为A <: Int ,则+的方法Int返回一个Int

So e + 1 is an Int and not an A (even if A must be an Int , anyway). 因此e + 1是一个Int而不是A (即使A必须是一个Int )。 Therefore, x.map(e => e + 1) returns a List[Int] and not a List[A] . 因此, x.map(e => e + 1)返回List[Int]而不是List[A] In order to return List[A] , you need some class A with a + method that also returns A , which you don't. 为了返回List[A] ,您需要一些带有+方法的类A ,该类也返回A ,但您不会这样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM