Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Setting nested Options to Some(value) #39

Open
oripwk opened this issue Oct 3, 2017 · 6 comments
Open

Setting nested Options to Some(value) #39

oripwk opened this issue Oct 3, 2017 · 6 comments

Comments

@oripwk
Copy link

oripwk commented Oct 3, 2017

Hi,

Given a nested chain of Options, is there a way to coerce the most inner one to Some?

The current operator .each allows traversing Options, but acts like map:

import com.softwaremill.quicklens._

case class C(d: Option[Int])
case class B(c: Option[C])
case class A(b: Option[B])

val a = A(b = None)

a.modify(_.b.each.c.each.d.each).setTo(3)  //  res0: A = A(None)

(the result is A(None), but how can we achieve a A(Some(B(Some(C(Some(3))))))?)

It could be useful if there were some operator (say, all) which can act as follows:

a.modify(_.b.all.c.all.d.all).setTo(3) //  res0: A = A(Some(B(Some(C(Some(3))))))
@adamw
Copy link
Member

adamw commented Oct 3, 2017

I'm afraid this is very option-chain-specific. Firstly, you wouldn't be able to use .modify, as there need not be a value. Secondly, if e.g. B had any other fields, there's nowhere to get their values from.

@oripwk
Copy link
Author

oripwk commented Oct 3, 2017

What about a variation of at(idx: Int) which doesn't throw IndexOutOfBoundsException, and instead enlarges the sequence so accommodate the new index? Such a method could also be adapted to Options if we look at them as sequences if length 1.

@adamw
Copy link
Member

adamw commented Oct 3, 2017

But what would you put in the indicies in between? Also, how would you initialize an "empty" object which would be added to the sequence?

@oripwk
Copy link
Author

oripwk commented Oct 3, 2017

Maybe a type class Zeroable[A] with default implementations for all the primitives?

A completely alternative solution would be a withHead[A](a: A) which can work for all sequences (including Option, Either, etc.)

@adamw
Copy link
Member

adamw commented Oct 9, 2017

Maybe Zeroable would work ... but I have the feeling that this takes the .each syntax a bit too far. Wouldn't, in such situations, just writing code in .setTo with the appropriate new instance creation logic be sufficient?

@oripwk
Copy link
Author

oripwk commented Oct 11, 2017

Yeah, on a second thought, there's no much difference between .setTo and my suggestion.

I guess you're right :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants