3

I have three class

class C {
  var id: String = _
}

class B {
  var c: List[C] = _
}

class A {
  var b: List[B] = _
}

I want to collect all "id" of class "C" instance, which are in a class "A" instance

val c1 = new C
c1.id = "data1"
val c2 = new C
c2.id = "data2"

val b = new B
b.c = c1::c2::Nil

val a = new A
a.b = b::Nil

Expected output for this sample code is List[String] having two element (ie, data1, data2) In imperative programming, I have achieved same with below code snippet

def collectCId(a: A): List[String] = {
  var collect = List[String]()
  for(tmpb <- a.b){
    for(tmpc <- tmpb.c){
      collect = tmpc.id :: collect
    }
  }
  collect
}

How can I achieve same in functional way?

Scala Version: 2.11

1
  • The names of variables are confusing : c being a List[C], maybe use cs instead? Commented Dec 12, 2018 at 13:17

1 Answer 1

8

With a for-comprehension:

def collectCId(a: A): List[String] = 
 for { 
   b <- a.b
   c <- b.c
 } yield c.id
Sign up to request clarification or add additional context in comments.

4 Comments

thanks @chirlo. I have one quick question. Is removal of "var" is termed as functional programming in objective way?
@user811602 , could you rephrase the question? Not sure what you're asking, sorry.
When I can say that I have written code in Functional Programming Paradigm? Is there any fixed set of rule for same? I know that this can be different question in SO, but a quick link will help me a lot.
There are several concepts normally associated with FP, like avoid side effects and immutability, but it's not all black and white, don't need to go all in. You can just use some FP principles in imperative programs and reap a lot of benefits. The Wikipedia page on FP has very good info to start with, and the FPiS would be my recommendation to get deeper into it , just dont' read it all at once, keep reading on demand as you get more familiar with FP.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.