Scala将List [Any]转换为List [Int]

时间:2014-03-16 20:23:58

标签: scala

有人可以帮我转换一下:

var l = List(1,2,"3")

进入这个:

var lNew = List(1,2,3)

这意味着我想转换一个带有部分整数的列表和部分整数作为字符串输入(例如" 27")到一个只有整数的新列表。问题是你不能在列表[任意]上使用.toInt。

非常感谢提前!

2 个答案:

答案 0 :(得分:19)

这应该是足够的解决方案:

 l.map(_.toString).map(_.toInt)

编辑:

关注soulcheck suggestion,甚至更好:

 l.map(_.toString.toInt)

答案 1 :(得分:2)

package com.example.rajat.fragments; import android.app.Fragment; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; public class FragmentClass extends Fragment { Button button; int count; String key1 = "counter"; Communicator comm; int key; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.i("onCreate", "onCreate() called"); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_activity, container, false); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); comm = (Communicator) getActivity(); button = (Button) getActivity().findViewById(R.id.button); if (savedInstanceState != null) { count = savedInstanceState.getInt(key1, 1); Log.e("onCreate", "onActivityCreated() called value of count :" + count); } button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { count++; key = count; Log.e("onCreate", "count value : " + count); comm.respond("The button is clicked " + count + " times"); } }); } @Override public void onSaveInstanceState(Bundle savedInstanceState) { super.onSaveInstanceState(savedInstanceState); savedInstanceState.putInt(key1, count); Log.d("onCreate", "onSavedInstanceState() called value of count :" + count); } 开始并引入String#toIntOption,如果需要的话,我们可以使@liosedhel's answer更加安全:

Scala 2.13