2017-09-17 14 views
1

私は、反復処理可能に関数を適用し、述語が真である最初にマッピングされた結果を返し組み合わせた地図と-見つける機能書いた:Scalaの型推論誤差

implicit class EnhancedIterable[A, B[X] <: Iterable[X]](it: B[A]) { 

    def mapAndFind[B](f: A => B, p: B => Boolean): Option[B] = { 
    var result: Option[B] = None 
    for (value <- it if result.isEmpty) { 
     val r = f(value) 
     if (p(r)) 
     result = Some(r) 
    } 
    result 
    } 

} 

を問題私がヒットします私は期待通りの機能を使用しようとコンパイルエラー:予想

val names = Seq("Jose", "Chris", "Carlos", "Stephan") 

names.mapAndFind(
    _.length, 
    _ > 5 // Error 
) 

型の不一致、:実際の(NotInferedB)=>ブール、:(Nothing)で=>どれ

物事がうまくコンパイルけれども私は型ヒントを使用する場合:

names.mapAndFind(
    _.length, 
    (len: Int) => len > 5 
) 

fからIntようなタイプB推測されていないのはなぜ?

答えて

1

Scalaフローの型推論との間の型の推論は、その中にはありません。

あなたは書くことができます。

implicit class EnhancedIterable[A, B[X] <: Iterable[X]](it: B[A]) { 
    def mapAndFind[B](f: A => B)(p: B => Boolean): Option[B] = { 
    var result: Option[B] = None 
    for (value <- it if result.isEmpty) { 
     val r = f(value) 
     if (p(r)) result = Some(r) 
    } 
    result 
    } 
} 

そして:

val names = Seq("Jose", "Chris", "Carlos", "Stephan") 
names.mapAndFind(_.length)(_ > 5) 

収量:

Some(6) 
+1

は完璧な理にかなっています。答えてくれてありがとう! –