简体   繁体   English

我们可以使用singleton .type作为类型参数吗?

[英]Can we use the singleton .type as a type parameter?

I was cobbling together an answer to this question: Scala mixin to class instance , where I showed a way of "mixing-in" another trait or class instance to an existing instance: 我正在拼凑这个问题的答案: Scala mixin到类实例 ,在那里我展示了一种“混入”另一个特征或类实例到现有实例的方法:

case class Person(name: String)
val dave = Person("Dave")
val joe  = Person("Joe")

trait Dog { val dogName: String }
val spot = new Dog { val dogName = "Spot" }

implicit def daveHasDog(p: dave.type) = spot

dave.dogName //"Spot"
joe.dogName  //error: value dogName is not a member of Person

So after the local implicit def, dave can effectively be used as a Person with Dog . 所以在本地隐式def之后, dave可以有效地用作Person with Dog My question is, if we wanted to define a method that takes a Person instance only where the Person has a Dog , how do we do it? 我的问题是,如果我们想要定义一个仅在PersonDog情况下接受Person实例的方法,我们该怎么做呢?

I can define a method such as 我可以定义一个方法,如

def showDog(pd: Person with Dog) = pd.name + " shows " + pd.dogName

however this is no good for dave since he is still just a Person , despite his implicit transformation abilities. 然而这对dave来说并不好,因为他仍然只是一个Person ,尽管他有隐含的转换能力。

I tried defining 我尝试过定义

trait Dog [T] { val dogName: String }
val spot = new Dog [dave.type] { val dogName = "Spot" }
def showDog(p: Person)(implicit dog: Dog[p.type]) = ...

but this is not legal, giving error: illegal dependent method type . 但这不合法,给出error: illegal dependent method type Any ideas? 有任何想法吗?

If you compile with -Ydependent-method-types , your original code will work with this definition of showDog : 如果使用-Ydependent-method-types编译, -Ydependent-method-types原始代码将使用showDog此定义:

scala> def showDog(p: Person)(implicit ev: p.type => Dog) = p.name + " shows " + p.dogName
showDog: (p: Person)(implicit ev: p.type => Dog)java.lang.String

scala> showDog(dave)
res1: java.lang.String = Dave shows Spot

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

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