Scala类型参数和Case类

Scala类型参数和Case类,scala,types,Scala,Types,我有这样一个函数: private def fixBrand[T]( item:T ) = item.copy(brand = item.brand.toLowerCase) 这不是编译---抱怨t没有函数副本。 现在我知道我要传递的每个项目都是一个案例类。 我怎样才能告诉编译器呢?这些案例类中的每一个都有一个“品牌”字段,但在对象层次结构方面是不相关的 我想我读到Scala2.10有一个特性,允许我使用T作为“一个东西”,它有函数x,y。。。?不过,我忘了那个功能叫什么了 您可以使用结构类型

我有这样一个函数:

private def fixBrand[T]( item:T ) = item.copy(brand = item.brand.toLowerCase)
这不是编译---抱怨t没有函数副本。 现在我知道我要传递的每个项目都是一个案例类。 我怎样才能告诉编译器呢?这些案例类中的每一个都有一个“品牌”字段,但在对象层次结构方面是不相关的


我想我读到Scala2.10有一个特性,允许我使用T作为“一个东西”,它有函数x,y。。。?不过,我忘了那个功能叫什么了

您可以使用结构类型:

def fixBrand[T <: { def copy(t: String): T; def brand: String }](item: T) = item.copy(item.brand.toLowerCase)

def fixBrand[T仅从您的函数来看,
T
是否有
copy
方法并不清楚,更不用说此方法也应该将
brand
作为参数之一

我认为你能得到的最接近的东西是视图边界的使用,比如

trait WithBrandCopyable[T] {
  def copy(brand: String): T
  def brand: String
}

object Classes {
  case class Class1(brand: String, number: Int)
  case class Class2(factor: Double, brand: String)

  implicit def class1ToWithBrandCopyable(obj: Class1) = new WithBrandCopyable[Class1] {
    def copy(brand: String) = obj.copy(brand = brand)
    def brand = obj.brand
  }

  implicit def class2ToWithBrandCopyable(obj: Class2) = new WithBrandCopyable[Class2] {
    def copy(brand: String) = obj.copy(brand = brand)
    def brand = obj.brand
  }
}

object Main {
  def fixBrand[T <% WithBrandCopyable[T]](obj: T) =
    obj.copy(brand = obj.brand.toLowerCase)

  def main(args: Array[String]) {
    import Classes._  // Import both classes and implicit conversions

    val obj1 = Class1("BrAnD1", 10)
    val obj2 = Class2(0.3, "BRAnd2")

    println(fixBrand(obj1))  // Prints Class1("brand1",10)
    println(fixBrand(obj2))  // Prints Class2(0.3,"brand2")
  }
}
trait与品牌可复制[T]{
def副本(品牌:字符串):T
def品牌:字符串
}
对象类{
案例类别1(品牌:String,编号:Int)
案例类别2(系数:双,品牌:字符串)
隐式def classatwithbrandcopyable(obj:Class1)=newwithbrandcopyable[Class1]{
def副本(品牌:字符串)=对象副本(品牌=品牌)
def品牌=obj品牌
}
隐式def class2ToWithBrandCopyable(obj:Class2)=newwithbrandcopyable[Class2]{
def副本(品牌:字符串)=对象副本(品牌=品牌)
def品牌=obj品牌
}
}
对象主体{

def fixBrand[T对于具有多个字段的case类的copy方法不起作用。这是因为copy方法不具有确切的签名。仅使用一个参数为copy创建重载也不起作用,因为您无法根据参数区分这两个重载。添加类似brandCopy的方法(t:String)对于每个类来说,这个解决方案都是可行的,但是你必须手动将这个方法添加到每个case类中。我认为你是对的……它对于copy不起作用,因为它是由编译器生成的,所以参数的数量未知。但是……我很高兴Lee提醒我这个术语:结构类型!