scala - Array of Arrays as Iterable of Iterables -
let's consider following definition add elements in nested iterable structure of ints:
def add(xss : iterable[iterable[int]]) : int = xss.map(_.sum).sum
however, evaluating following expression yields type error:
scala> add(array(array(1,2,3))) <console>:9: error: type mismatch; found : array[array[int]] required: iterable[iterable[int]] add(array(array(1,2,3))) ^
the function works expected other iterables (like lists). how can avoid error? what's rationale it? guess arrays being native java, don't know specifics details in case.
thanks
it doesn't work because scala need use 2 implicit conversion in row go array[array[int]]
iterable[iterable[int]]
, (purposefully) doesn't do.
you specify outer array
's type :
scala> add(array[iterable[int]](array(1,2,3))) res4: int = 6
or transform elements iterable[int]
(thus bypassing implicit conversion) :
scala> add(array(array(1,2,3)).map(_.toiterable)) res5: int = 6
the problem comes fact scala's array[t]
representation java's t[]
. makes array[t]
behave usual scala collection implicit conversion in predef.
from array
's documentation :
two implicit conversions exist in scala.predef applied arrays: conversion mutable.arrayops , conversion mutable.wrappedarray (a subtype of scala.collection.seq). both types make available many of standard operations found in scala collections api. conversion arrayops temporary, operations defined on arrayops return array, while conversion wrappedarray permanent operations return wrappedarray.
the conversion arrayops takes priority on conversion wrappedarray.
Comments
Post a Comment