Parameter capture types varargs

I would like to define a method that accepts varargs, so that I get the types with which it was called even in the case of zeros.

def foo(args: Any*) = ....

val s: String = null

foo(1, s) // i'd like to be able to tell in foo that args(0) is Int, args(1) is String
+3
source share
3 answers

In terms of the original question, I am sure this is not possible.

Not knowing exactly what you are trying to achieve (i.e. why it should be a list of arbitrary types with variable lengths), it is difficult to offer an alternative. However, there are two things that come to my mind when I read a question that might be an option for you: The default argument values in conjunction with (requires Scala 2.8+) and HListthe data type (less likely).

+4
source

Any , . instanceof :

def foo(args: Any*) = for (a <- args) a match {
  case i: Int =>
  case s: String =>
  case _ =>
}

, .

, :

def foo[A](arg1: A)
def foo[A, B](arg1: A, arg2: B)
def foo[A, B, C](arg1: A, arg2: B, arg3: C)
...
+6

Since you use Anyas a type, you cannot get the type of arguments. A type Anyhas no method getClass(it is not a reference class at all). See http://www.scala-lang.org/node/128 for more details .

What you can try:

def foo(args: Any*) = args.map { arg => {
  arg match {
    case reference:AnyRef => reference.getClass.toString
    case null => "null"
}}}

val s: String = null

val result = foo("a", 1, 'c', 3.14, s, new Object, List(1), null)

result.foreach(println)

It is output:

class java.lang.String
class java.lang.Integer
class java.lang.Character
class java.lang.Double
null
class java.lang.Object
class scala.collection.immutable.$colon$colon
null
+3
source

Source: https://habr.com/ru/post/1744098/


All Articles