Call can throw, but it is not marked with 'try' and the error is not handled
Kotlinにある mapNotNull を実装しようとして(Swiftなので名前はmapNotNilの方が適切か?)
Call can throw, but it is not marked with 'try' and the error is not handled
というエラーが出ました。
extension Array {
func mapNotNull<ElementOfResult>(_ transform: (Element) throws -> ElementOfResult) rethrows -> [ElementOfResult] {
return self.compactMap {
$0
}.map {
transform($0) // ここでエラー
}
}
}
メソッド定義を
func mapNotNull<ElementOfResult>(_ transform: (Element) -> ElementOfResult) -> [ElementOfResult]
と変えた場合、エラーは消えるのですが、これだと mapNotNull に渡したクロージャが例外を起こすコードを書いた場合コンパイルエラー(to non-throwing function typeのようなコンパイルエラー)となるため、本来の map や compactMap と違う挙動となるため、よくないと考えています(本来のmap や comapctMap に近づけたいです)
うまく rethrows させるにはどう書けばよいのでしょうか?
追記:
そもそもElementが配列オブジェクトができたタイミングで型が決まるので、mapNotNull は実現できないきもしてきました...
さらに追記
OptionalType もしくは OptionalProtocol はどういったテクニックなのでしょうか?
に別の質問を足しました