如何在scala中返回值类型为String的Map

时间:2016-08-19 08:43:01

标签: scala

    class myclass(object):
      lst_of_A=[]
      def __init__(self, Attr_A, Attr_B, Attr_C):
        self.A=Attr_A
        self.B=[Attr_B]
        self.C=[Attr_C]
        self.lst_of_A.append(Attr_A)
      def append_to_existing_entry(self, Attr_B, Attr_C):
        self.B.append(Attr_B)
        self.C.append(Attr_C)

预期输出

    my_lst_of_classes=[]
    for el in read_in_data:
      try:
        ind=my_lst_of_classes[0].lst_of_A.index(el[0])
        my_lst_of_classes[index].append_to_existing_entry(el[1],el[2])
      except:
        my_lst_of_classes.append(myclass(el[0],el[1],el[2]))

但是在运行时我得到错误

{\"$date\":\"1947-11-13T00:00:00.000Z\"}

1 个答案:

答案 0 :(得分:3)

您有三种选择:

(A)从连接中删除参数类型C,因为返回值始终为String

def join[K,A,B](custs:Map[K,A],txns:Map[K,B]) :Map[K, String]= {
    for((k,va) <- custs; vb <- txns.get(k)) yield k -> va.toString()+"|"+ vb.toString()
}

(B)添加通用组合器函数并保持方法参数:

def join[K,A,B, C](custs:Map[K,A],txns:Map[K,B], combiner: (A, B) => C) :Map[K, C]= {
    for((k,va) <- custs; vb <- txns.get(k)) yield k -> combiner(va, vb)
}

(C)始终返回一个元组,从而删除参数类型C;并在其结果上使用mapValues以组合元组元素:

def join[K,A,B](custs:Map[K,A],txns:Map[K,B]) :Map[K, C]= {
    for((k,va) <- custs; vb <- txns.get(k)) yield k -> (va, vb)
}