Variable defined w/ def gives "Missing name with which to set the channel variable"

workflow convert_sam_to_bam {
    take:
    genrf_ch

    main:
    // def sam_to_bam_ch = Channel.empty()
    sam_to_bam_ch = Channel.empty()
    if (!params.sam.isBlank())
    {
        channel
            .fromPath(params.sam)
            .map{tuple(string_prefix(it.toString(), "convert_sam_to_bam"), it)}
            .combine(genrf_ch)
            .set{sam_ch}
        

        /*
        sam_to_bam(sam_ch)
            .set{sam_to_bam_ch}
        */
        sam_to_bam_ch = sam_to_bam(sam_ch)
    }
    
    emit:
    sam_to_bam_ch
}

In the code above, I get an error if I define sam_to_bam_ch with def.

When sam_to_bam_ch is defined with def, within the if statement, the statement

sam_to_bam(sam_ch)
        .set{sam_to_bam_ch}

Gives the error

ERROR ~ Missing name with which to set the channel variable

The statement

sam_to_bam_ch = sam_to_bam(sam_ch)

Gives the error

Missing workflow output parameter: sam_to_bam_ch

The code runs either way if I don’t use def to define sam_to_bam_ch.

I’d appreciate clarification on a few things:

  1. If I don’t use def when I define sam_to_bam_ch, will it have global scope?
  2. I prefer to keep variable scope local when possible, is there a way to make sam_to_bam have local scope (while still being emittable) and get this code to work?
  3. Why do the two statements calling sam_to_bam produce different error messages?
  4. Why does def sam_to_bam_ch generate any error message at all in this case? My understanding of Groovy’s scoping is that its scope should extend into the if block.

The scope of variables within the Nextflow process/workflow blocks is a bit unintuitive. There are two community pages that explain a bit about this here and here.

You will see in the link above that global variables can not be set to local variables. That’s what you’re doing when you get the output channel from the sam_to_bom process and try to assign to sam_to_bam_ch that was created with def. It’s not related to inside or outside the if structure.

The second error is a different one. You’re failing to add a channel to sam_to_bam_ch and then Nextflow complains that you said the subworkflow would emit sam_to_bam_ch but the channel doesn’t exist.

Thanks for those links, that’s helpful.

1 Like

Please, mark my answer as a solution if it solved your problem :wink: