how match mixed type of scala higher-kinder types feature with java generic type?

柔情痞子 提交于 2019-12-11 12:25:09

问题


my project is mixed java and scala language, but some type mismatch error occur and I think it's a common problem in term of java and scala communicate. I organized the stage with simple classes. Environment is java 1.8 and scala 2.11.7

class Item[+T](name: String)

//ready use Item as MM type
class Packet[+MM[_]]

object GenS extends App {
  //use Item class
  def doWithPacket(packet: Packet[Item]) = {}

  //type error occur on packetFormJava variable form java
  val packetFormJava = GetGenJ.newPacketInJava
  doWithPacket(packetFormJava)

  //run well
  val packetFromScala = new Packet[Item]
  doWithPacket(packetFromScala)
}

and the java class simple as this:

public class GetGenJ {
    public static Packet<Item> newPacketInJava() {
        return new Packet<Item>();
    }
}

The compile error encounter:

Error:(16, 16) type mismatch;  
 found   : Packet[Item[_]]  
 required: Packet[Item]  
  doWithPacket(packetFormJava)  
                  ^

any help or advice thanks.


回答1:


In other word, how does the java represent scala's Packet[Item[_]] type?

It doesn't. Java simply doesn't have higher-kinded types. The information that MM is higher-kinded is hidden inside @ScalaSignature.

When you write Packet<Item>, you are using a raw type (which, in turn, can't be represented in Scala); you couldn't use Item<Something> inside newPacketInJava.



来源:https://stackoverflow.com/questions/34542191/how-match-mixed-type-of-scala-higher-kinder-types-feature-with-java-generic-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!