Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to make string as parameters that include several strings

my code as follow:

var args = "arg1,arg2" //come from external and also many e.g. arg3,arg4 ...
df.select(args.split(","):_*)

then got the errors:

:31: error: no `: *' annotation allowed here (such annotations are only allowed in arguments to *-parameters) df.select(args.split(","):*)

any body could give help? thanks.

like image 312
Autumn Avatar asked Dec 23 '22 11:12

Autumn


2 Answers

Well... the use of varargs syntax (: _*) is allowed only for functions which expect variable arguments.

scala> def iAcceptVarArgs(strings: String*) = println(strings)
// iAcceptVarArgs: (strings: String*)Unit

scala> iAcceptVarArgs("str1", "str2")
// WrappedArray(str1, str2)

scala> iAcceptVarArgs(List("str1", "str2"): _*)
// List(str1, str2)

It will not work for functions which do not expect variable arguments,

scala> def iDoNotAcceptVarArgs(s: String) = println(List(s))
// iDoNotAcceptVarArgs: (s: String)Unit

scala> iDoNotAcceptVarArgs(List("str1"): _*)
// <console>:14: error: no `: _*' annotation allowed here
// (such annotations are only allowed in arguments to *-parameters)
//         iDoNotAcceptVarArgs(List("str1"): _*)
                                           ^

Since Dataframe.select has following signature,

def select(col: String, cols: String*): DataFrame

It means that the first argument is fixed and only second argument onwards can be varargs

You should use pattern-matching in this case,

val args = "arg1,arg2"

val dfSelection = args.split(",").toList match {
  case a1 :: tail => df.select(a1, tail: _*)
  case Nil => df // well... what to do here ?
}
like image 136
sarveshseri Avatar answered Mar 06 '23 02:03

sarveshseri


can you try this

var args = "arg1,arg2" //come from external and also many e.g. arg3,arg4 ...
var x = args.split(",").toList;
df.select(x.head,x.tail:_*)
like image 45
Nikhil Kumar K Avatar answered Mar 06 '23 03:03

Nikhil Kumar K