如何将字符串列表转换为案例类?

时间:2020-03-20 23:42:45

标签: scala

我有一个字符串列表,类似List("12345:$", "12346:$"),我唯一需要的是数字"12345",它在冒号之前,这是我的案例类,如何获取数字并进行转换到案例课?正则表达式是做到这一点的好方法吗?

case class Account(accountId: String) 

2 个答案:

答案 0 :(得分:2)

不需要正则表达式。仅从case class Account(accountId: String) List("123:$", "456:$").map(s => Account(s.split(":")(0))) // res1: List[Account] = List(Account("123"), Account("456")) 的结果中获取第一个元素就足够了:

val pattern = """(\d*):.*""".r

List("123:$", "456:$", "xyz:$").collect{ case pattern(num) => Account(num) }
// res2: List[Account] = List(Account("123"), Account("456"))

如果首选Regex:

import React, { Component } from 'react';
import GlobalStyle from './styles/Global';
import {
    Route,
    BrowserRouter,
    Switch
  } from "react-router-dom";

import '../src/css/App.css'
import './css/About.css'
import './css/AddBathroom.css'
import Navbar from "./components/navbar/Navbar";
import Home from "./components/Home";
import About from "./components/About";
import MapContainer from './components/MapContainer';
import MapContainerComp from './components/MapContainerComp'

import firebase from 'firebase';
import StyledFirebaseAuth from 'react-firebaseui/StyledFirebaseAuth';

const uiConfig = {
    // Popup signin flow rather than redirect flow.
    signInFlow: 'popup',
    // Redirect to /signedIn after sign in is successful. Alternatively you can provide a callbacks.signInSuccess function.
    signInSuccessUrl: '',
    // We will display Google and Facebook as auth providers.
    signInOptions: [
        firebase.auth.GoogleAuthProvider.PROVIDER_ID,
        firebase.auth.FacebookAuthProvider.PROVIDER_ID
    ]
};

class App extends Component {
    constructor(props) {
        super(props);

        this.state = {
            navbarOpen: false,
            public: {},
            isSignedIn:false,
            uid: ''
        };
        this.favoritesRef = firebase.database().ref("mybathrooms");
        this.publicRef = firebase.database().ref("allBathrooms");
        this.publicRef.on('value', (snapshot) => {
            let data = snapshot.val();
            this.setState({public: data})
        })
    }



    componentDidMount() {
        this.unregisterAuthObserver = firebase.auth().onAuthStateChanged(
            (user) => this.setState({isSignedIn: !!user})
        );
    }

    componentWillUnmount() {
        this.unregisterAuthObserver();
    }


    handleNavbar = () => {
        this.setState({ navbarOpen: !this.state.navbarOpen });
    };

    render() {
            if (!this.state.isSignedIn) {
                return (
                    <div className="row">
                    <div className="column">
                    <div role="heading">
                        <h1>Bathroom Finder</h1>
                        <p>Please sign-in for more functionality:</p>
                        <StyledFirebaseAuth uiConfig={uiConfig} firebaseAuth={firebase.auth()}/>
                        <Home />
                    </div>
                        <div className="column">
                        <MapContainer />
                        </div>
                    </div>
                    </div>

                );
            }
        return (
            <>
                <Navbar
                    navbarState={this.state.navbarOpen}
                    handleNavbar={this.handleNavbar}
                />
                <BrowserRouter>
                    <div role="separator">
                        <Switch>
                            <Route exact path={`/`} render={ (routerProps) => <Home routerProps={routerProps}/>} />
                            <Route path="/home" render= {props =>
                                <div className="home-container">
                                <div className="row">
                                    <div className="column">
                                    <Home />
                                    </div>
                                <div className="column">
                                    <MapContainer />
                                </div>
                                </div>
                                </div>
                            } />
                            <Route path="/bathroom" render= {props =>
                                <div>
                                    <MapContainerComp uid={this.state.uid}/>
                                </div>    
                            } />
                            <Route path="/about" render= {props =>
                                <div>
                                    <About />
                                </div>    
                            } />                        
                        </Switch>
                    </div>
                </BrowserRouter>

                <GlobalStyle />

                <div className="login" role="application">
                    <div className="row">
                    <h1>You are logged in to Bathroom Finder!</h1>
                    <p>Welcome {firebase.auth().currentUser.displayName}! You are now signed-in!</p>
                    </div>
                    <div className= "row">
                    <button className="signout" onClick={() => firebase.auth().signOut().then(function () {
                        console.log("signed out");
                    })}>Sign-out</button>
                    </div>
                </div>
            </>



        );
    }
}

export default App;`

答案 1 :(得分:1)

Welcome to Scala 2.13.1 (OpenJDK 64-Bit Server VM, Java 1.8.0_222).
Type in expressions for evaluation. Or try :help.

scala> case class Account(accountId: String)
defined class Account

scala> List("123:$", "456:$").map{ case s"$id:$$" => Account(id) }
res0: List[Account] = List(Account(123), Account(456))