Scala推断的类型参数 - 类型范围推断为'Nothing' [英] Scala inferred type arguments - Type bounds inferring to 'Nothing'

查看:166
本文介绍了Scala推断的类型参数 - 类型范围推断为'Nothing'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图写一个简单的查询monad,并且无法正常使用我的通用类型注释。



我第一次尝试去如下所示(为了简明起见,大大简化了)

pre codease case class Person(val name:String)
抽象类Schema [T ]
对象人们扩展了Schema [Person]

case class Query [U<:Schema [T],T](schema:U){< ---- Type signature
def结果:Seq [T] = ...
def其中(f:U =>操作)= ...
}

类TypeText extends Application {
val query = Query(People)< ---- Type type inference
}

编译器不喜欢这样,因为它不能推断'T'的类型。


错误:推断类型参数[People.type,Nothing]不符合方法apply的类型参数bounds [U<:Schema [T],T]



hile试验我发现使用视图边界可以按预期工作

  case class Query [U<%Schema [T],T ](schema:U){

(注意使用视图边界<%类型绑定<:)



然而,在我对类型系统的有限理解中,因为我期望Schema的实际子类(而不仅仅是可转换性) T],我会假设类型绑定<是在这里使用的正确界限?



如果是这样的话,我错过了什么 - 怎么做我给编译器足够的提示,以便在使用类型边界而不是视图边界时正确推断T?

在两个类型参数之间,您可以使用类似于以下内容的类:

  case class Query [U,T](schema:U) ev:U <:< Schema [T]){...} 

请参阅 Scala Language Spec 获取更多信息。


I'm attempting to write a simple query monad and am having trouble getting my generic type annotations correct.

My first attempt went as follows (vastly simplified for conciseness)

case class Person( val name: String )
abstract class Schema[T]    
object People extends Schema[Person]

case class Query[U <: Schema[T], T]( schema: U ) {      <---- Type signature
    def results: Seq[T] = ...
    def where( f: U => Operation ) = ...
}

class TypeText extends Application {
    val query = Query( People )                     <---- Type inference fails
}

The compiler didn't like this, as it couldn't infer the type of 'T'.

error: inferred type arguments [People.type,Nothing] do not conform to method apply's type parameter bounds [U <: Schema[T],T]

While experimenting I found that using view bounds instead works as expected

case class Query[U <% Schema[T], T]( schema: U ) {

(Note the use of view bound "<%" instead of type bound "<:")

However in my limited understanding of the type system, since I'm expecting an actual subclass (and not just convertibility) of Schema[T], I would assume type bound "<:" is the correct bounds to be using here?

If this is the case, what am I missing - how do I give the compiler enough hints to infer T correctly when using type bounds instead of view bounds?

解决方案

In order to encode the relationship between the two type parameters, you can use something like

case class Query[U, T](schema: U)(implicit ev: U <:< Schema[T]) { ... }

See §4.3 and §4.4 of the Scala Language Spec for more info.

这篇关于Scala推断的类型参数 - 类型范围推断为'Nothing'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆