Scala type (inference) issue?

亡梦爱人 提交于 2019-12-08 18:53:29

问题


I'm developing a REST webservice in Scala using the Jersey JAX-RS reference implementation and I'm getting a strange error.

I'm trying to create a ContentDisposition object using the ContentDisposition.ContentDispositionBuilder.

ContentDisposition.ContentDispositionBuilder has two types T extends ContentDisposition.ContentDispositionBuilder and V extends ContentDisposition. The method type of ContentDisposition returns a builder instance.

The code

val contentDisposition = ContentDisposition.`type`(MediaType.APPLICATION_OCTET_STREAM).build()

works however

val contentDisposition = ContentDisposition.`type`(MediaType.APPLICATION_OCTET_STREAM).fileName("dummy").build()

produces the compiler error

error: value build is not a member of ?0
val contentDisposition = ContentDisposition.`type`(MediaType.APPLICATION_OCTET_STREAM).fileName("dummy").build()
                                                                                                         ^

(Note that type needs to be put in "quotation marks" because it's a keyword in Scala)

fileName of ContentDispositionBuilder returns an instance of T so this should actually work.

I don't get this. Any idea? I'm using Scala 2.9.0.1 by the way.

Update:

This works. But why do I need the casting here?

val contentDisposition = ContentDisposition.`type`(MediaType.APPLICATION_OCTET_STREAM)
  .fileName("dummy")
  .asInstanceOf[ContentDisposition.ContentDispositionBuilder[_,_]]
  .build()

回答1:


I guess type inference can only go so far... You can probably do it in two lines, without having to do any casts; have you tried this?

val something=ContentDisposition.`type`(MediaType.APPLICATION_OCTET_STREAM)
val contentDisposition=something.fileName("dummy").build()

or maybe

val builder=ContentDisposition.`type`(MediaType.APPLICATION_OCTET_STREAM).fileName("dummy")
val contentDisposition=builder.build()


来源:https://stackoverflow.com/questions/7253779/scala-type-inference-issue

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